All Downloads are FREE. Search and download functionalities are using the official Maven repository.
Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.github.chen0040.gp.utils.QuickSort Maven / Gradle / Ivy
package com.github.chen0040.gp.utils;
import java.util.Comparator;
import java.util.List;
/**
* Created by xschen on 17/5/2017.
* Provide my own quick sort instead of java's list sort which becomes unstable when comparing tp solutions
*/
public class QuickSort {
public static void sort(List a, Comparator compare){
int lo = 0;
int hi = a.size()-1;
sort(a, lo, hi, compare);
}
private static void sort(List a, int lo, int hi, Comparator comparator){
if(lo >= hi) return;
if(hi - lo < 7){
insertionSort(a, lo, hi, comparator);
return;
}
int j = partition(a, lo, hi, comparator);
sort(a, lo, j-1, comparator);
sort(a, j+1, hi, comparator);
}
private static void insertionSort(List a, int lo, int hi, Comparator comparator){
for(int i=lo+1; i <= hi; ++i){
for(int j=i-1; j >= lo; --j){
if(comparator.compare(a.get(j+1), a.get(j)) < 0){
CollectionUtils.exchange(a, j, j+1);
} else {
break;
}
}
}
}
private static int partition(List a, int lo, int hi, Comparator comparator) {
int i, j;
T v = a.get(lo);
i = lo;
j = hi+1;
while(true){
while(comparator.compare(a.get(++i), v) < 0){
if(i >= hi) break;
}
while(comparator.compare(v, a.get(--j)) < 0) {
if(j <= lo) break;
}
if(i >= j) {
break;
}
CollectionUtils.exchange(a, i, j);
}
CollectionUtils.exchange(a, lo, j);
return j;
}
}