June 2018 Update
This commit is contained in:
parent
ba8067c3b7
commit
22f33d4004
5278 changed files with 84726 additions and 14379 deletions
|
|
@ -6,41 +6,25 @@ public class DutchNationalFlag {
|
|||
RED, WHITE, BLUE
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args){
|
||||
DutchColors[] balls = new DutchColors[12];
|
||||
|
||||
DutchColors[] values = DutchColors.values();
|
||||
Random rand = new Random();
|
||||
for (int i = 0; i < balls.length; i++)
|
||||
balls[i] = values[rand.nextInt(values.length)];
|
||||
|
||||
for (int i = 0; i < balls.length; i++)
|
||||
balls[i]=values[rand.nextInt(values.length)];
|
||||
System.out.println("Before: " + Arrays.toString(balls));
|
||||
|
||||
dutchNationalFlagSort(balls);
|
||||
Arrays.sort(balls);
|
||||
System.out.println("After: " + Arrays.toString(balls));
|
||||
|
||||
System.out.println("After : " + Arrays.toString(balls));
|
||||
}
|
||||
|
||||
private static void dutchNationalFlagSort(DutchColors[] items) {
|
||||
int lo = 0, mid = 0, hi = items.length - 1;
|
||||
|
||||
while (mid <= hi)
|
||||
switch (items[mid]) {
|
||||
case RED:
|
||||
swap(items, lo++, mid++);
|
||||
break;
|
||||
case WHITE:
|
||||
mid++;
|
||||
break;
|
||||
case BLUE:
|
||||
swap(items, mid, hi--);
|
||||
break;
|
||||
boolean sorted = true;
|
||||
for (int i = 1; i < balls.length; i++ ){
|
||||
if (balls[i-1].compareTo(balls[i]) > 0){
|
||||
sorted=false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void swap(DutchColors[] arr, int a, int b) {
|
||||
DutchColors tmp = arr[a];
|
||||
arr[a] = arr[b];
|
||||
arr[b] = tmp;
|
||||
}
|
||||
System.out.println("Correctly sorted: " + sorted);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue