Skip to content

Commit 93c463f

Browse files
committed
Add ShuffleSort
1 parent 1ff1c3c commit 93c463f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.Arrays;
2+
import java.util.Random;
3+
4+
public class ShuffleSort {
5+
6+
private Random random = new Random();
7+
8+
public void sort(int[] list) {
9+
while (!isSorted(list))
10+
shuffle(list);
11+
}
12+
13+
private void shuffle(int[] list) {
14+
for (int i = list.length - 1; i > 0; i--) {
15+
int randomIndex = random.nextInt(i);
16+
17+
int temp = list[i];
18+
list[i] = list[randomIndex];
19+
list[randomIndex] = temp;
20+
}
21+
}
22+
23+
private boolean isSorted(int[] list) {
24+
Integer prev = null;
25+
for (Integer elem : list) {
26+
if (prev != null && prev.compareTo(elem) > 0) return false;
27+
prev = elem;
28+
}
29+
30+
return true;
31+
}
32+
33+
public static void main(String[] args) {
34+
35+
int[] list = { 33, 0, 29, 4, 44, 3 };
36+
37+
ShuffleSort shuffleSort = new ShuffleSort();
38+
shuffleSort.sort(list);
39+
40+
System.out.println("Sorted list:");
41+
System.out.println(Arrays.toString(list));
42+
}
43+
}

0 commit comments

Comments
 (0)