forked from Hithomelabs/Princeton1
Merge branch '3-way-quicksort' into benchmark
This commit is contained in:
commit
265aa3ca85
@ -0,0 +1,23 @@
|
||||
package com.hithomelabs.clients.module7;
|
||||
|
||||
import com.hithomelabs.princeton1.common.Apple;
|
||||
import com.hithomelabs.princeton1.module7.Quick;
|
||||
import com.hithomelabs.princeton1.module7.ThreeWayQuick;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class ThreeWayQuickSortClient {
|
||||
|
||||
public static void main(String[] args) {
|
||||
int size = 100;
|
||||
Apple[] apples = new Apple[size];
|
||||
ThreeWayQuick<Apple> quick = new ThreeWayQuick<>();
|
||||
|
||||
for (int i = 0; i < apples.length; i++) {
|
||||
apples[i] = new Apple(new Random().nextInt(10));
|
||||
}
|
||||
quick.sort(apples);
|
||||
for (int i = 0; i < apples.length; i++)
|
||||
System.out.println(apples[i]);
|
||||
}
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.hithomelabs.princeton1.module7;
|
||||
|
||||
import com.hithomelabs.princeton1.module5.AbstractCustomSorts;
|
||||
|
||||
public class ThreeWayQuick<E> extends AbstractCustomSorts<E> {
|
||||
@Override
|
||||
public void sort(E[] arr) {
|
||||
coreSortingLogic(arr);
|
||||
}
|
||||
|
||||
private void coreSortingLogic(E[] arr) {
|
||||
int N = arr.length;
|
||||
threeWaySort(arr, 0, N - 1);
|
||||
}
|
||||
|
||||
private void threeWaySort(E[] arr, int lo, int hi) {
|
||||
|
||||
if(hi <= lo)
|
||||
return;
|
||||
int k = hi;
|
||||
int i = lo + 1;
|
||||
int j = lo;
|
||||
|
||||
while (true) {
|
||||
if (((Comparable<E>) arr[i]).compareTo(arr[j]) < 0) {
|
||||
exch(arr, i, j++);
|
||||
i++;
|
||||
} else if (((Comparable<E>) arr[i]).compareTo(arr[j]) > 0)
|
||||
exch(arr, i, k--);
|
||||
else {
|
||||
i++;
|
||||
}
|
||||
|
||||
if (k < i)
|
||||
break;
|
||||
}
|
||||
threeWaySort(arr, lo, j - 1);
|
||||
threeWaySort(arr, k + 1, hi);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user