File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ //What is Cycle sort
2+ //When we are given numbers from 1 to N (not necessarily exactly from 1 to N) we use cycle sort.
3+ //It sorts the entire array in one single pass.
4+ //The basic idea behind cycle sort is the sorted array will contain elements on their correct index.
5+ //For eg. - elements from 1 to 5 will be on index 0 to 4 in the sorted array.
6+ //Advantages are :- It sorts the array in-place and does not require additional memory for temporary variables.
7+
8+ //Here is the link for leetcode question which is solved using cycle sort.
9+ //https://leetcode.com/problems/missing-number/
10+
11+
12+ public class CycleSort {
13+
14+ public static void swap (int arr [],int start ,int end )
15+ {
16+ int temp =arr [start ];
17+ arr [start ]=arr [end ];
18+ arr [end ]=temp ;
19+ }
20+
21+ public static void cycleSort (int arr [])
22+ {
23+ int i =0 ;
24+ while (i <arr .length )
25+ {
26+ int correctIndex =arr [i ]-1 ; //correctIndex is the index that has the value equal to correctIndex-1.
27+ if (arr [i ]==arr [correctIndex ]) //if value of index i is equal to the value at correctIndex i.e., equal to (value of index i) -1.
28+ //index number (arr[i]) should contain (arr[i]-1)
29+ {
30+ i ++;
31+ }
32+ else
33+ {
34+ swap (arr ,i ,correctIndex );
35+ }
36+ }
37+
38+ for (int x :arr )
39+ {
40+ System .out .print (x +" " );
41+ }
42+ }
43+
44+ public static void main (String [] args ) {
45+ int arr []={3 ,5 ,2 ,1 ,4 };
46+ cycleSort (arr );
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments