排序是什么?
排序是对随机一组数字进行从大到小(或从小到大)的排列。
排序算法的稳定性
常见的排序算法
算法工具类介绍
public class SortUtil {
public static int[] a = new int[10];
public static int[] create() {
for (int i = 0; i < 10; i++) {
Random random = new Random();
a[i] = random.nextInt(10);
}
return a;
}
public static void show(int[] a) {
for (int i : a) {
System.out.print(i + " ");
}
System.out.println();
}
public static void exchange(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static boolean less(int i, int j) {
return i < j;
}
}
选择排序
public class Selection {
public static void main(String[] args) {
int[] a = SortUtil.create();
SortUtil.show(a);
int N = a.length;
for (int i = 0; i < N; i++) {
int min = i;
for (int j = i + 1; j < N; j++) {
if (SortUtil.less(a[j], a[min])) {
min = j;
}
}
SortUtil.exchange(a, i, min);
}
SortUtil.show(a);
}
}
插入排序
public class Insertion {
public static void main(String[] args) {
int[] a = SortUtil.create();
SortUtil.show(a);
int N = a.length;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0 && SortUtil.less(a[j], a[j - 1]); j--) {
SortUtil.exchange(a, j, j - 1);
}
}
SortUtil.show(a);
}
}
希尔排序
public class Shell {
public static void main(String[] args) {
int[] a = SortUtil.create();
SortUtil.show(a);
int N = a.length;
int h = 1;
while (h < N / 3) {
h = 3 * h + 1;
}
while (h >= 1) {
for (int i = 0; i < N; i++) {
for (int j = i; j >= h && SortUtil.less(a[j], a[j - 1]); j -= h) {
SortUtil.exchange(a, j, j - 1);
}
}
h /= 3;
}
SortUtil.show(a);
}
}
归并排序
public class Merge {
private static int[] aux = new int[SortUtil.a.length];
public static void main(String[] args) {
int[] a = SortUtil.create();
SortUtil.show(a);
sort(a, 0, SortUtil.a.length - 1);
SortUtil.show(a);
}
private static void sort(int[] a, int lo, int hi) {
if (hi <= lo) {
return;
}
int mid = lo + (hi - lo) / 2;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
public static void merge(int[] a, int lo, int mid, int hi) {
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
for (int k = lo; k <= hi; k++) {
if (i > mid)
a[k] = aux[j++];
else if (j > hi)
a[k] = aux[i++];
else if (SortUtil.less(aux[j], aux[i]))
a[k] = aux[j++];
else
a[k] = aux[i++];
}
}
}
快速排序
|