forked from MakeContributions/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cyclic-sort.java
70 lines (54 loc) · 2.25 KB
/
cyclic-sort.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Arrays;
public class cyclicSort {
public static void main(String[] args)
{
int[] array1 = {4,5,2,3};
int[] array2 = {2, 1, 5, 2, 9, 1, 2, 3, 3, 4, 4, 5, 6, 7, 8};
Sort(array1);
Sort(array2);
System.out.println(Arrays.toString(array1));
System.out.println(Arrays.toString(array2));
}
static void Sort(int[] array)
{
// step 1: loop from the beginning of the array to the second to last item
for (int currentIndex = 0; currentIndex < array.length - 1; currentIndex++)
{
// step 2: save the value of the item at the currentIndex
int item = array[currentIndex];
// step 3: save a copy of the current index
int currentIndexCopy = currentIndex;
// step 4: loop through all indexes that proceed the currentIndex
for (int i = currentIndex + 1; i < array.length; i++)
if (array[i] < item)
currentIndexCopy++;
// step 5: if currentIndexCopy has not changed, the item at the currentIndex is already in the correct position
if (currentIndexCopy == currentIndex)
continue;
// step 6: skip duplicates
while (item == array[currentIndexCopy])
currentIndexCopy++;
// step 7: swap
int temp = array[currentIndexCopy];
array[currentIndexCopy] = item;
item = temp;
// step 8: repeat steps 4, 6 and 7 above as long as we can find values to swap
while (currentIndexCopy != currentIndex)
{
// step 9: save a copy of the currentIndex
currentIndexCopy = currentIndex;
// step 10: repeat step 4
for (int i = currentIndex + 1; i < array.length; i++)
if (array[i] < item)
currentIndexCopy++;
// step 10: repeat step 6
while (item == array[currentIndexCopy])
currentIndexCopy++;
// step 10: repeat step 7
temp = array[currentIndexCopy];
array[currentIndexCopy] = item;
item = temp;
}
}
}
}