public class Sort {
// 选择插入的实现,递增,数组a的待排区间是[low,high](直接插入排序)
public void insertSort(int a[], int low, int high) {
for (int i = low + 1; i < high; i++) {
if (a[1] < a[i + 1]) {
int temp = a[i];
a[i] = a[i - 1];
int j = i - 2;
for (; j >= low && temp < a[j]; j--) {
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
for (int i : a) {
System.out.print(i + " ");
}
}
// 折半插入排序的实现
public void binInsertSort(int a[], int low, int high) {
for (int i = low + 1; i <= high; i++) {
int temp = a[i];
int hi = i - 1;
int lo = low;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (temp < a[mid]) {
hi = mid - 1;
} else {
lo = mid + 1;
}
}
for (int j = i - 1; j > hi; j--) {
a[j + 1] = a[j];
}
a[hi + 1] = temp;
}
}
// 希尔排序的算法实现
public void shellSort(int a[], int low, int high, int delta[]) {
for (int k = 0; k < delta.length; k++) {
this.shellInsert(a, low, high, delta[k]);// 一趟步长为的delta[k]的直接插入排序
}
}
private void shellInsert(int a[], int low, int high, int deltaK) {
for (int i = low + deltaK; i <= high; i++) {
if (a[i] < a[i - deltaK]) {
int temp = a[i];
int j = i - deltaK;
for (; j >= low && temp < a[j]; j -= deltaK) {
a[j + deltaK] = a[j];
}
a[j + deltaK] = temp;
}
}
}
// 冒泡排序算法实现
public void bubbleSort(int a[], int low, int high) {
int n = high - low + 1;
for (int i = 1; i < n; i++) {
for (int j = low; j <= high - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
// 快速排序算法实现
public void quickSort(int a[], int low, int high) {
if (low < high) {
int pa = this.partition(a, low, high);
this.quickSort(a, low, pa - 1);
this.quickSort(a, pa + 1, high);
}
}
// 实现一次划分
private int partition(int a[], int low, int high) {
int pivot = a[low]; // 使用作为枢轴元素
while (low < high) {// 从两端交替向内扫描
while (low < high && a[high] >= pivot) {
high--;
}
while (low < high && a[low] <= pivot) {
low++;
}
a[high] = a[low];
}
a[low] = pivot;
return low;
}
// 选择排行的实现,递增
public void selectSort(int a[], int low, int high) {
for (int k = low; k < high - 1; k++) {
int min = k;
for (int i = min + 1; i <= high; i++) {
if (a[i] < a[min]) {
min = i;
}
}
if (k != min) {
int temp = a[k];
a[k] = a[min];
a[min] = temp;
}
}
}
// 堆排序的实现
/**
* 输入:数据元素数组a 输出:对a排序
*/
public void heapSort(int a[]) {
int n = a.length - 1;
for (int i = n / 2; i >= 1; i--) {
this.headAdjust(a, i, n); //初始化建堆
}
for (int i = n; i > 1; i--) {//不断输出对顶元素并调整a[1...i-1]为新堆
int temp = a[1];//交换堆顶与堆底元素
a[1] = a[i];
a[i] = temp;
this.headAdjust(a, 1, i - 1);//调整
}
}
/**
* 输入:数据元素数组a,数组的待调整区间[low , high] 输出:调整a[low , high]使之成为大顶堆
*/
private void headAdjust(int a[], int low, int high) {
int temp = a[low];
for (int j = 2 * low; j <= high; j *= 2) {
if (j < high && a[j] < a[j + 1]) {
j++;
}
if (temp >= a[j])
break;
a[low] = a[j];
low = j;
}
a[low] = temp;
}
}