这两个都是比较重要的排序算法
在Java中,Arrays.sort()选择了根据不同的参数类型,来使用不同的排序算法。如果是原始数据类型则使用三向切分的快速排序,对引用类型则使用归并排序。
Java实现快速排序
import java.util.Arrays;
import java.util.List;
public class QuickSort {
/** Prevents instantiation. */
private QuickSort() {}
public static <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 lo, int hi) {
if (lo < hi) {
int pivot = randomPartition(array, lo, hi);
doSort(array, lo, pivot - 1);
doSort(array, pivot, hi);
}
}
private static <T extends Comparable<T>> int randomPartition(T[] array, int lo, int hi) {
/*
* 加个随机数与高位交换的目的是
* 如果交换后的高位比pivot小, 则高位遍历的第一下就能锁定值
* 如果交换后的高位比pivot大, 则正常遍历
* 如果原先高位就比pivot小, 替换后此元素离低位更近, 高低位同时遍历时影响不大
*/
int randomIndex = lo + (int)(Math.random()*(hi - lo + 1));
exch(array, randomIndex, hi);
return partition(array, lo, hi);
}
private static <T extends Comparable<T>> int partition(T[] array, int lo, int hi) {
int mid = (lo + hi) / 2;
T pivot = array[mid];
while (lo <= hi) {
while (less(array[lo], pivot)) {
++lo;
}
while (less(pivot, array[hi])) {
--hi;
}
if (lo <= hi) {
exch(array, lo, hi);
++lo;
--hi;
}
}
return lo;
}
/*
* Helper sorting functions.
*/
/** exchange a[i] and a[j] */
private static <T> boolean exch(T[] a, int i, int j) {
T swap = a[i];
a[i] = a[j];
a[j] = swap;
return true;
}
/** is x < y ? */
private static <T extends Comparable<T>> boolean less(T x, T y) {
return x.compareTo(y) < 0;
}
/** Check if array is sorted - useful for debugging. */
private static <T extends Comparable<T>> boolean isSorted(T[] a) {
for (int i = 1; i < a.length; i++) {
if (less(a[i], a[i - 1]))
return false;
}
return true;
}
/** Just print list */
private static void print(List<?> toPrint) {
toPrint.stream()
.map(Object::toString)
.map(str -> str + " ")
.forEach(System.out::print);
System.out.println();
}
/** Prints an array */
private static void print(Object[] toPrint) {
System.out.println(Arrays.toString(toPrint));
}
// Driver Program
public static void main(String[] args) {
Integer[] array = {3, 4, 1, 32, 0, 1, 5, 12, 2, 5, 7, 8, 9, 2, 44, 111, 5};
print(array);
QuickSort.sort(array);
print(array);
}
}
Scala实现快速排序
object QuickSort {
def main(args: Array[String]): Unit = {
println(quickSort(List(3, 5, 1, 8, 2, 9, 4, 6, 7)))
}
def quickSort(list: List[Int]): List[Int] = list match {
case Nil => Nil
case head :: tail =>
val (left, right) = tail.partition(_ < head)
quickSort(left) ::: head :: quickSort(right)
}
}
Java实现归并排序
import java.util.Arrays;
/**
* The {@code Merge} class provides static methods for sorting an
* array using merge sort.
* <p>详情介绍见博客 <a href="http://...">我要去非洲晒太阳</a>
* @author Floyd
*/
public class MergeSort {
/** Prevents instantiation. */
private MergeSort() {}
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
// auxiliary array
Comparable[] aux = new Comparable[a.length];
doSort(a, aux, 0, a.length-1);
}
// merge sort a[lo..hi] using auxiliary array aux[lo..hi]
public static void doSort(Comparable[] a, Comparable[] aux, int lo, int hi) {
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
doSort(a, aux, lo, mid);
doSort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
}
// stably merge a[lo .. mid] with a[mid+1 ..hi] using aux[lo .. hi]
private static void merge(Comparable[] a,Comparable[] aux, int lo, int mid, int hi) {
// copy to aux[]
for (int i = lo; i <= hi; i++) aux[i] = a[i];
// merge back to a[]
int l = lo, r = mid + 1;
for (int i = lo; i <= hi; i++) {
if (l > mid) {
a[i] = aux[r++];
} else if (r > hi) {
a[i] = aux[l++];
} else {
a[i] = less(aux[l],aux[r]) ? aux[l++] : aux[r++];
}
}
}
/*
* Helper sorting functions.
*/
/** exchange a[i] and a[j] */
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/** is x < y ? */
private static boolean less(Comparable x, Comparable y) {
return x.compareTo(y) < 0;
}
public static void main(String[] args) {
//Integer[] arr = { 1, 4, 5, 6, 7, 2, 3, 8, 9 };
Integer[] arr = new Integer[100];
for (int i = 0; i < 100; i++) {
arr[i] = (int) (Math.random() * 100);
}
MergeSort.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
Scala实现归并排序
object MergeSort {
def mergeSort(array: Array[Int]): Array[Int] = {
def sort(array: Array[Int]): Array[Int] = {
MS(array, 0, array.length - 1)
}
def MS(array: Array[Int], low: Int, high: Int): Array[Int] = {
if (low < high) {
val mid = (low + high) / 2
MS(array, low, mid)
MS(array, mid + 1, high)
merge(array, low, mid, high)
} else {
array
}
}
def merge(array: Array[Int], low: Int, mid: Int, high: Int): Array[Int] = {
// copy subarrays
val left = array.slice(low, mid + 1)
val right = array.slice(mid + 1, high + 1)
var i = 0
var j = 0
var k = low
while (k < high + 1) {
// must check if empty to avoid exceptions
if (i > left.length - 1) {
array(k) = right(j)
j = j + 1
} else if (j > right.length - 1) {
array(k) = left(i)
i = i + 1
} else if (left(i) <= right(j)) {
array(k) = left(i)
i = i + 1
} else {
array(k) = right(j)
j = j + 1
}
k = k + 1
}
array
}
sort(array)
}
}