- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathCyclicSort.java
28 lines (28 loc) · 768 Bytes
/
CyclicSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
publicclassCyclicSort {
publicstaticvoidmain(String[] args) {
//test case
int[] arr = {3, 1, 5, 4, 2};
cycleSort(arr);
for (inti = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
//cycle sort
publicstaticvoidcycleSort(int[] arr){
inti = 0;
while(i < arr.length){
intcorrect = arr[i] - 1;
if(arr[i] != arr[correct]){
swap(arr, i, correct);
}else{
i++;
}
}
}
//swap function
publicstaticvoidswap(int[] arr, intfirst, intsecond){
inttemp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}