public class SortUtil {
public static void main(String[] args) {
int[] data = { -1, 1, 42, 22, 61, 44, 12, 34 };// data[0]是辅助空间
System.out.print("the original array:");
print(data);
// insertSort(data);
// bInsertSort(data);
// bubbleSort(data);
quickSort(data, 1, data.length - 1);
print(data);
}
private static void print(int[] data) {
for (int i = 1; i < data.length; i++) {
System.out.print(data[i] + " ");
}
System.out.println();
}
/**
* 直接插入排序 时间复杂度:平均情况-O(n2) 最坏情况-O(n2) 辅助空间:O(1) 稳定性:稳定
*/
private static void insertSort(int[] data) {
int i, j;
for (i = 1; i < data.length; i++) {
if (data[i] < data[i - 1]) {
data[0] = data[i];
for (j = i - 1; data[0] < data[j]; j--) {
data[j + 1] = data[j];
}
data[j + 1] = data[0];
}
}
}
/**
* 折半插入排序 时间复杂度:平均情况-O(n2) 稳定性:稳定
*/
private static void bInsertSort(int[] data) {
int i, j, high, low, m;
for (i = 1; i < data.length; i++) {
data[0] = data[i];
low = 0;
high = i - 1;
while (low <= high) {
m = (low + high) / 2;
if (data[0] < data[m]) {
high = m - 1;
} else {
low = m + 1;
}
}
for (j = i - 1; j >= high + 1; j--) {
data[j + 1] = data[j];
}
data[high + 1] = data[0];
}
}
/**
* 时间复杂度:平均情况—O(n2) 最坏情况—O(n2) 辅助空间:O(1) 稳定性:稳定
*/
private static void bubbleSort(int[] data) {
for (int i = data.length - 1; i >= 2; i--) {
for (int j = 1; j < i; j++) {
if (data[j] > data[j + 1]) {
data[0] = data[j];
data[j] = data[j + 1];
data[j + 1] = data[0];
}
}
}
}
/**
* 时间复杂度:平均情况—O(nlog2n) 最坏情况—O(n2) 辅助空间:O(log2n) 稳定性:不稳定
*/
private static void quickSort(int[] data, int low, int high) {
if (low < high) {
int pivotloc = partition(data, low, high);
quickSort(data, low, pivotloc - 1);
quickSort(data, pivotloc + 1, high);
}
}
private static int partition(int[] data, int low, int high) {
data[0] = data[low];
int pivotkey = data[low];
while (low < high) {
while (low < high && data[high] >= pivotkey) {
high--;
}
data[low] = data[high];
while (low < high && data[low] <= pivotkey) {
low++;
}
data[high] = data[low];
}
data[low] = data[0];
return low;
}
}