code:
public static void insertSort(int[] array) {
for (int i = 1; i < array.length; i++) {
int temp = array[i];
int j = i - 1;
for (; j >= 0 && array[j] > temp; j--) {
array[j + 1] = array[j]; //将大于temp的值整体后移一个单位
}
array[j + 1] = temp;
}
}
2. 希尔排序
code:
public static void shellSort(int[] array) {
int i;
int j;
int temp;
int len = array.length;
for (int gap = len / 2; gap > 0; gap /= 2) {
for (i = gap; i < len; i++) {
temp = array[i];
for (j = i - gap; j >= 0 && array[j] > temp; j -= gap) {
array[j + gap] = array[j];
}
array[j + gap] = temp;
}
}
}
3.冒泡排序
public static void bubbleSort(int[] array) {
int len = array.length;
int temp = 0;
for (int i = 0; i < len -1; i++) {
for (int j = 0; j < len-1-i; j++) {
if (array[j] > array[j+1]) {
tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
}
}
}
}
4.快速排序
public static void getMiddle(int[] array, int low, int high) {
int temp = array[low]; //第一个元素作为基点
while (low < high) {
while (low < high && array[high] > temp) {
high--;
}
array[low] = array[high]; //比基点小的元素放到左边
while (low < high && array[low] < temp) {
low++;
}
array[high] = array[low]; //比基点大的元素放到右边
}
array[low] = temp;
return low;
}
public static quickSort(int[] array, int low, int high) {
if (low < high) {
int middle = getMiddle(array, low, high);
quickSort(array, low, middle - 1);
quickSort(array, middle+1, high)
}
}
5.直接选择排序
public static void selectionSort(int[] array) {
int len = array.length;
int temp = 0;
for (int i = 0; i < len-1; i++) {
int min = i;
for (int j = i+1; j < len-1; i++) {
if (array[j] < array[min]) {
min = j;
}
}
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
6.堆排序
public static void buildMaxHeap(int[] array, int lastIndex) {
for (int i = (lastIndex-1)/2; i >= 0; i--) {
int k = i;//从最后一个节点的父节点开始
while (2*k+1 <= lastIndex) {
int biggerIndex = 2*k+1;
if (biggerIndex < lastIndex) {//存在右节点
if (array[biggerIndex] < array[biggerIndex+1]) {
biggerIndex++;
}
}
if (array[k] < array[biggerIndex]) {
swap(array, k, biggerIndex)
k = biggerIndex;
} else {
break;
}
}
}
}
public static void swap(int[] array, int i; int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(string[] args) {
int[] array = {4,5,3,7,6};
int len = array.length;
for (int i = 0; i < len; i++) {
buildMaxHeap(array, len-1-i);
swap(array, 0, len-1-i)
}
}
7.归并排序
public static void merge(int[] array, int low, int middle, int high) {
int temp[] = new int[high - low + 1];
int i = low;
int j = middle+1;
int k = 0;
while (low <= middle && j <= high) {
if (array[i] < array[j]) {
temp[k] = array[i];
i++;
} else {
temp[k] = array[j]
j++;
}
k++;
}
while (low <= middle) {
temp[k] = array[i];
i++;
k++;
}
while (j <= high) {
temp[k] = array[j]
j++;
k++;
}
for (int i = 0; i < high - low + 1; i++) {
array[low + i] = temp[i];
}
}
public static void sort(int array, int low, int high) {
int middle = (low + high) / 2;
if (low < high) {
sort(array, low, middle);
sort(array, middle+1, high);
merge(array, low, middle, high);
}
}