-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathcyclic sort.java
More file actions
43 lines (33 loc) · 769 Bytes
/
cyclic sort.java
File metadata and controls
43 lines (33 loc) · 769 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
35
36
37
38
39
40
41
42
// java program to check implement cycle sort
import java.util.*;
public class MissingNumber {
public static void main(String[] args)
{
int[] arr = { 3, 2, 4, 5, 1 };
int n = arr.length;
System.out.println("Before sort :");
System.out.println(Arrays.toString(arr));
CycleSort(arr, n);
}
static void CycleSort(int[] arr, int n)
{
int i = 0;
while (i < n) {
int correctpos = arr[i] - 1;
if (arr[i] < n && arr[i] != arr[correctpos]) {
swap(arr, i, correctpos);
}
else {
i++;
}
}
System.out.println("After sort : ");
System.out.print(Arrays.toString(arr));
}
static void swap(int[] arr, int i, int correctpos)
{
int temp = arr[i];
arr[i] = arr[correctpos];
arr[correctpos] = temp;
}
}