public int[] mergeSortC(int[] array, int low, int heigh) {
if (low < heigh) {
int mid = (low + heigh) / 2;
mergeSortC(array, low, mid);
mergeSortC(array, mid + 1, heigh);
merge(array, low, mid, heigh);
}
return array;
}
public void merge(int[] array, int low, int mid, int heigh) {
int[] temp = new int[heigh - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= heigh) {
if (array[i] < array[j]) {
temp[k++] = array[i++];
} else {
temp[k++] = array[j++];
}
}
while (i <= mid) {
temp[k++] = array[i++];
}
while (j <= heigh) {
temp[k++] = array[j++];
}
for (int n = 0; n < temp.length; n++) {
array[n + low] = temp[n];
}
}
public void quickSort(int[] array) {
quickSortC(array, 0, array.length - 1);
}
public void quickSortC(int[] array, int leftIndex, int rightIndex) {
if (leftIndex >= rightIndex) return;
int left = leftIndex;
int right = rightIndex;
int key = array[left];
while (left < right) {
while (right > left && array[right] >= key) {
right--;
}
array[left] = array[right];
while (left < right && array[left] <= key) {
left++;
}
array[right] = array[left];
}
array[left] = key;
quickSortC(array, leftIndex, left - 1);
quickSortC(array, right + 1, rightIndex);
}
//第K大元素的算法思想來源於快排
public void quickSortK(int[] array, int leftIndex, int rightIndex, int K) {
if (leftIndex >= rightIndex) return;
int left = leftIndex;
int right = rightIndex;
int key = array[left];
while (left < right) {
while (right > left && array[right] >= key) {
right--;
}
array[left] = array[right];
while (left < right && array[left] <= key) {
left++;
}
array[right] = array[left];
}
//經歷過交換後,left放到了它在數組中對應的位置
array[left] = key;
//這裏是與快排區別的地方,不需要全都排序,只需要在K的方向上進行排序
if (left + 1 == K)
return;
else if (left + 1 > K) {
quickSortK(array, leftIndex, left - 1, K);
} else {
quickSortK(array, right + 1, rightIndex, K);
}
//最後取數組中第k-1個元素就是第K大的元素
}