排序算法的穩(wěn)定性
假定在待排序的記錄序列中,存在多個具有相同的關(guān)鍵字的記錄,若經(jīng)過排序,這些記錄的相對次序保持不變,即在原序列中,r[i]=r[j],且r[i]在r[j]之前,而在排序后的序列中,r[i]仍在r[j]之前,則稱這種排序算法是穩(wěn)定的;否則稱為不穩(wěn)定的。
1. 使用快速排序,然后取出第k大的數(shù)字
2. 使用堆排序
基本思路:
- 將無序序列構(gòu)建成一個堆,根據(jù)升序降序需求選擇大頂堆或小頂堆
- 將堆頂元素與末尾元素交換,將最大元素沉到數(shù)組末端
3.重新調(diào)整結(jié)構(gòu),使其滿足堆定義,然后繼續(xù)交換堆頂元素與當(dāng)前末尾元素,反復(fù)執(zhí)行調(diào)整+交換步驟,直到整個序列有序
3. 快速選擇算法
這種方法算是對上面方法的一種優(yōu)化,一般面試如果你使用了上面的方法后,面試官都會問你如何優(yōu)化。
- 時間復(fù)雜度平均情況為O(n),最壞情況為O(n^2)
代碼:
class Solution {
Random random = new Random();
public int findKthLargest(int[] nums, int k) {
return quickSelect(nums, 0, nums.length - 1, nums.length - k);
}
public int quickSelect(int[] a, int l, int r, int index) {
int q = randomPartition(a, l, r);
if (q == index) {
return a[q];
} else {
return q < index ? quickSelect(a, q + 1, r, index) : quickSelect(a, l, q - 1, index);
}
}
public int randomPartition(int[] a, int l, int r) {
int pivod_index = random.nextInt(r - l + 1) + l;
swap(a, pivod_index, r); // 把參考值放到最右邊,方便將除了自己之外的值都遍歷一遍
return partition(a, l, r);
}
public int partition(int[] a, int l, int r) {
int x = a[r], pivod_index = l; // 取出基準(zhǔn)值,進(jìn)行比較
for (int i = l; i < r; i++) {
if (a[i] <= x) { // 小于基準(zhǔn)值,進(jìn)行交換
swap(a, pivod_index, i);
pivod_index++;
}
}
swap(a, pivod_index, r);
return pivod_index;
}
public void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}