基础类
public interface SortAlgorithm {
<T extends Comparable<T>> T[] sort(T[] unsorted);
}
final class SortUtils {
static <T> boolean swap(T[] array, int idx, int idy){
T swap = array[idx];
array[idx] = array[idy];
array[idy] = swap;
return true;
}
static <T extends Comparable<T>> boolean less(T v, T w) {
return v.compareTo(w) < 0;
}
static void print(List<?> toPrint){
toPrint.stream()
.map(Object::toString)
.map(str -> str + " ")
.forEach(System.out::print);
System.out.println();
}
static void print(Object[] toPrint){
System.out.println(Arrays.toString(toPrint));
}
}
冒泡排序
public class BubbleSort implements SortAlgorithm{
public <T extends Comparable<T>> T[] sort(T[] array) {
int last = array.length;
//Sorting
boolean swap;
do {
swap = false;
for (int count = 0; count < last-1; count++) {
if (less(array[count], array[count + 1])) {
swap = swap(array, count, count + 1);
}
}
last--;
} while (swap);
return array;
}
选择排序
public class SelectionSort implements SortAlgorithm {
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
// Initial index of min
int min = i;
for (int j = i +1 ; j < n; j++) {
if (SortUtils.less(array[j], array[min])) {
min = j;
}
}
// Swapping if index of min is changed
if (min != i) {
SortUtils.swap(array, i , min);
}
}
return array;
}
插入排序
public class InsertionSort implements SortAlgorithm{
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
for (int j = 1; j < array.length; j++) {
// Picking up the key(Card)
T key = array[j];
int i = j - 1;
while (i >= 0 && less(key, array[i])) {
array[i + 1] = array[i];
i--;
}
// Placing the key (Card) at its correct position in the sorted subarray
array[i + 1] = key;
}
return array;
}
}
快速排序
public class QuickSort implements SortAlgorithm {
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
doSort(array, 0, array.length - 1);
return array;
}
private static <T extends Comparable<T>> void doSort(T[] array, int left, int right) {
if (left < right) {
int pivot = partition(array, left, right);
doSort(array, left, pivot - 1);
doSort(array, pivot , right);
}
}
private static <T extends Comparable<T>> int partition(T[] array, int left, int right) {
int mid = (left + right) / 2;
T pivot = array[mid];
while(left <= right) {
while(less(array[left], pivot)){
++left;
}
while(less(pivot, array[right])) {
--right;
}
if(left <= right) {
swap(array, left, right);
++left;
--right;
}
}
return left;
}
}