Skip to content

Commit a597ee4

Browse files
author
Niklas
committed
Random Sort optimiert auf 1/4 der Zeit
1 parent 4e26a6f commit a597ee4

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

src/designPattern/strategy/RandomSort.java

+19-8
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,40 @@
33
import java.util.Arrays;
44

55
public class RandomSort implements SorterIF {
6+
int[] sorted;
67

78
@Override
89
public int[] sort(int[] sourceArray) {
10+
sorted = Arrays.copyOf(sourceArray, sourceArray.length);
11+
Arrays.sort(sorted);
12+
long time = System.currentTimeMillis();
913
int[] targetArray = Arrays.copyOf(sourceArray, sourceArray.length);
14+
int i = 0;
1015
while (!isSorted(targetArray)) {
1116
shuffle(targetArray);
17+
if (i%10000000 == 0 && i != 0) {
18+
System.out.println("Zwischenstand " + i + " in " + (System.currentTimeMillis() - time) / 1000.0);
19+
}
20+
i++;
1221
}
1322
return targetArray;
1423
}
1524

1625
private void shuffle(int[] i) {
17-
for (int x = 0; x < i.length; ++x) {
26+
for (int x = 0; x < i.length; x++) {
1827
int index1 = (int) (Math.random() * i.length);
19-
int index2 = (int) (Math.random() * i.length);
20-
int a = i[index1];
21-
i[index1] = i[index2];
22-
i[index2] = a;
28+
int a = i[x];
29+
i[x] = i[index1];
30+
i[index1] = a;
2331
}
2432
}
2533

26-
private boolean isSorted(int[] i){
27-
for (int x = 0; x < i.length - 1; ++x) {
28-
if (i[x] > i[x + 1]) {
34+
private boolean isSorted(int[] toCheck){
35+
if (toCheck.length == 1) {
36+
return true;
37+
}
38+
for (int i = 1;i < toCheck.length; i++) {
39+
if (toCheck[i - 1] > toCheck[i]) {
2940
return false;
3041
}
3142
}

0 commit comments

Comments
 (0)