korobushk

cyclicSort

May 10th, 2021 (edited)
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.75 KB | None | 0 0
  1. public static void main(String[] args) {
  2.         int [] myArray = cyclicSort(new int[] {3,4,6,2,1,5});
  3.         for(int i=0; i <myArray.length; i++){
  4.             System.out.println(myArray[i]);
  5.         }
  6.  
  7.     }
  8.  
  9.     public static int [] cyclicSort(int a[]){
  10.         int i = 0 ;
  11.  
  12.         while(i<a.length) {
  13.             // 0 1 2 3 4 5
  14.             // 3,4,6,2,1,5
  15.             // 6 4 3 2 1 5
  16.             // 5 4 3 2 1 6
  17.             // 1 4 3 2 5 6
  18.             // 1 2 3 4 5 6
  19.  
  20.  
  21.             //                        i = 0;       ||       i = 0;    ||    i = 1           |   i = 2
  22.             int j = a[i]-1;     //j = 2 || j = 5   || j = 4  || j = 0 ||  j = 3   || j = 1  |   j = 2
  23.             if (a[i] != a[j]) { //0 != 6 || 6 != 5 || 5 != 1 || 1!= 1 ||  4!= 2   || 2 == 2 |   3 = 3  end
  24.                 int temp = a[i];
  25.                 a[i] = a[j];
  26.                 a[j] = temp;
  27.             } else {
  28.                 i++;
  29.             }
  30.         }
  31.         return a;
  32.     }
  33.  
  34.  
  35. }
  36.  
Add Comment
Please, Sign In to add comment