1、冒泡排序
public class Bubble {
public void sort(int[] a) {
for (int i = a.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (a[j] > a[j + 1]) {
a[j] = a[j] ^ a[j + 1];
a[j + 1] = a[j] ^ a[j + 1];
a[j] = a[j] ^ a[j + 1];
}
}
}
}
}
2、简单选择排序
public class Select {
public void sort(int[] a) {
for (int i = 0; i < a.length; i++) {
int tempElem = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[tempElem]) {
tempElem = j;
}
}
if (tempElem != i) {
int temp = a[i];
a[i] = a[tempElem];
a[tempElem] = temp;
}
}
}
}
3、直接插入排序
public class Insert {
public void sort(int[] a) {
for (int i = 1; i < a.length; i++) {
int temp = a[i];
int j = i - 1;
for (; j >= 0 && a[j] > temp; j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
}
4、折半插入排序
public class Half {
public void sort(int[] a) {
for (int i = 1; i < a.length; i++) {
int low = 0;
int high = i - 1;
int temp = a[i];
while (low <= high) {
int mid = (low + high) / 2;
if (temp > a[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
int j = i - 1;
for (; j > high; j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
}
5、快速排序
public class Quick {
public void sort(int[] a, int left, int right) {
int l = left;
int r = right;
int temp = a[(l + r) / 2];
while (l < r) {
while (a[l] < temp) {
l++;
}
while (a[r] > temp) {
r--;
}
if (l <= r) {
int t = a[l];
a[l] = a[r];
a[r] = t;
l++;
r--;
}
}
if (l < right) {
sort(a, l, right);
}
if (left < r) {
sort(a, left, r);
}
}
}
6、希尔排序
public class ShellSort {
public void sort(int[] a) {
int d = a.length;
while (true) {
d = (int) Math.ceil(d / 2);
for (int i = 0; i < d; i++) {
for (int j = i + d; j < a.length; j += d) {
int temp = a[j];
int k = j - d;
for (; k >= 0 && a[k] > temp; k -= d) {
a[k + d] = a[k];
}
a[k + d] = temp;
}
}
if (d == 1) {
break;
}
}
}
}
7.睡眠排序和猴子排序(误)
import java.util.Random;
public class Sort {
public static void main(String[] args) throws InterruptedException {
int[] a = {100, 31, 520, 630, 705, 802, 906, 9};
System.out.println("睡眠排序:");
sleepSort(a);
Thread.sleep(3000);
System.out.println("猴子排序:");
monkeySort(a);
for (int i : a) {
System.out.print(i + "\t");
}
}
public static void sleepSort(int[] a) {
for (int i : a) {
new Thread(() -> {
try {
Thread.sleep(i);
System.out.println(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
public static void monkeySort(int[] a) {
Random random = new Random();
while (!isSorted(a)) {
int i = random.nextInt(a.length);
int j = random.nextInt(a.length);
while (i == j) {
j = random.nextInt(a.length);
}
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
private static boolean isSorted(int[] a) {
if (a == null || a.length <= 1) {
return true;
}
for (int i = 1; i < a.length; i++) {
if (a[i - 1] > a[i]) {
return false;
}
}
return true;
}
}
排序结果: