-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycleSort_1toN.java
More file actions
32 lines (25 loc) · 647 Bytes
/
Copy pathcycleSort_1toN.java
File metadata and controls
32 lines (25 loc) · 647 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
31
package Sorting;
import java.util.Arrays;
public class cycleSort_1toN {
public static void main(String[] args) {
int[] nums = {3,5,2,1,4};
System.out.println(Arrays.toString(sort(nums)));
}
static int[] sort(int[] arr){
int i = 0;
while (i < arr.length){
int correct = arr[i] - 1;
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;
}
}