-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathcyclic-sort.java
More file actions
34 lines (31 loc) · 821 Bytes
/
cyclic-sort.java
File metadata and controls
34 lines (31 loc) · 821 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
32
33
34
import java.util.Arrays;
import java.util.Scanner;
public class CyclicSort {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Limit: ");
int l=in.nextInt();
int[] arr=new int[l];
for(int i=0;i<l;i++){
arr[i]=in.nextInt();
}
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;
}
}