Skip to content

Commit 8927aa9

Browse files
authored
Merge pull request #101 from Milishparsai007/milishparsai007
Added cycle sort
2 parents 8c34b23 + 1455062 commit 8927aa9

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

0 commit comments

Comments
 (0)