-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleSort_0toN.java
More file actions
30 lines (25 loc) · 656 Bytes
/
Copy pathCycleSort_0toN.java
File metadata and controls
30 lines (25 loc) · 656 Bytes
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
29
30
package Sorting;
import java.util.Arrays;
public class CycleSort_0toN {
public static void main(String[] args) {
int[] nums = {4,3,2,0,1};
System.out.println(Arrays.toString(cyclicSort(nums)));
}
static int[] cyclicSort(int[] arr) {
int i = 0;
while (i < arr.length) {
int correct = arr[i];
if (arr[i] != arr[correct]) {
swap(arr, i, correct);
} else {
i++;
}
}
return arr;
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}