forked from vedant1771/Hactoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcyclicsort.java
More file actions
30 lines (27 loc) · 703 Bytes
/
cyclicsort.java
File metadata and controls
30 lines (27 loc) · 703 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
// importing libraries for array
import java.util.Arrays;
// create public class
public class cyclicsort {
public static void main(String[] args){
int[] arr = {1,3,2,5,4};
sort(arr);
System.out.println(Arrays.toString(arr));
}
static void 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++;
}
}
}
static void swap(int[] arr,int first, int second){
int temp =arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}