forked from pabulaner/vivi
BogoSort
This commit is contained in:
parent
7704486f5b
commit
82e4b75df0
35
list/src/main/java/de/vivi/list/BogoSort.java
Normal file
35
list/src/main/java/de/vivi/list/BogoSort.java
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package de.vivi.list;
|
||||||
|
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
public class BogoSort implements ByteSort {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ByteList sort(ByteList list) {
|
||||||
|
bogoSort(list);
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void bogoSort(ByteList list) {
|
||||||
|
while (isSorted(list) == false) {
|
||||||
|
shuffleList(list);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void shuffleList(ByteList list) {
|
||||||
|
Random r = new Random();
|
||||||
|
for (int i = list.size() - 1; i > 0; i--) {
|
||||||
|
int j = r.nextInt(i);
|
||||||
|
byte temp = list.get(i);
|
||||||
|
list.set(i, list.get(j));
|
||||||
|
list.set(j, temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isSorted(ByteList list) {
|
||||||
|
for (int i = 1; i < list.size(); i++)
|
||||||
|
if (list.get(i) < list.get(i - 1))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -28,8 +28,9 @@ public class Main {
|
|||||||
list.add((byte) 5);
|
list.add((byte) 5);
|
||||||
list.add((byte) -86);
|
list.add((byte) -86);
|
||||||
list.add((byte) 3);
|
list.add((byte) 3);
|
||||||
list.add((byte) 5);
|
list.add((byte) 55);
|
||||||
list.add((byte) -100);
|
list.add((byte) -100);
|
||||||
|
list.add((byte) -20);
|
||||||
|
|
||||||
//
|
//
|
||||||
// System.out.println(list);
|
// System.out.println(list);
|
||||||
@ -157,14 +158,16 @@ public class Main {
|
|||||||
private static void testSortVivi(ByteList list) {
|
private static void testSortVivi(ByteList list) {
|
||||||
ByteSort bubble = new BubbleSort();
|
ByteSort bubble = new BubbleSort();
|
||||||
ByteSort merge = new MergeSort();
|
ByteSort merge = new MergeSort();
|
||||||
// ByteSort bogo = new BogoSort();
|
ByteSort bogo = new BogoSort();
|
||||||
|
|
||||||
// sort the lists with the sorting algorithm
|
// sort the lists with the sorting algorithm
|
||||||
// bubble.sort(list.copy());
|
// bubble.sort(list.copy());
|
||||||
// System.out.println("bubblesort " + bubble.sort(list.copy()));
|
// System.out.println("bubblesort " + bubble.sort(list.copy()));
|
||||||
System.out.println();
|
// System.out.println();
|
||||||
System.out.println(merge.sort(list.copy()));
|
// System.out.println(merge.sort(list.copy()));
|
||||||
// merge.sort(list.copy());
|
// merge.sort(list.copy());
|
||||||
// bogo.sort(list.copy());
|
// bogo.sort(list.copy());
|
||||||
|
System.out.println();
|
||||||
|
System.out.println(bogo.sort(list.copy()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user