1 快排
#include <iostream>
using namespace std;
int Partition(int a[],int left,int right)
{
if (left<right)
{
int i = left;
int j = right;
int x = a[i];
while (i<j)
{
while (i<j&&a[j]>x)
j--;
if (i<j) {
a[i] = a[j];
i++;
}
while (i<j&&a[i]<x)
i++;
if (i<j) {
a[j] = a[i];
j--;
}
}
return i;
}
}
void quick_sort(int a[], int left, int right)
{
if (left < right)
{
int x = a[left];
int i = Partition(a, left, right);
a[i] = x;
quick_sort(a, left, i - 1);
quick_sort(a, i + 1, right);
}
}
2 以O(n)查找a[n]中第k大的元素:
#include<iostream>
#include<stdio.h>
using namespace std;
int Partition(int *L, int low, int high)
{
int temp = L[low];
int pt = L[low]; //哨兵
while (low != high)
{
while (low < high && L[high] >= pt)
high--;
L[low] = L[high];
while (low < high && L[low] <= pt)
low++;
L[high] = L[low];
}
L[low] = temp;
return low;
}
void QSort(int *L, int low, int high) //快速排序
{
int pl;
if (low < high)
{
pl = Partition(L, low, high);
QSort(L, low, pl - 1);
QSort(L, pl + 1, high);
}
}
void findk(int k, int *L, int low, int high)
{
int temp;
temp = Partition(L, low, high);
if (temp == k - 1)
{
cout << "第" << temp + 1 << "大的数是:" << L[temp] << endl;
}
else if (temp>k - 1)
findk(k, L, low, temp - 1);
else
findk(k, L, temp + 1, high);
}
int main()
{
int a[10] = { 15,25,9,48,36,100,58,99,126,5 }, i, j, k;
cout << "排序前:" << endl;
for (i = 0; i<10; i++) {
cout << a[i] << " ";
}
cout << endl;
cout << "请输入你要查找第k大的数:" << endl;
cin >> k;
findk(k, a, 0, 9); //查找第k大的数不需要全部排序
QSort(a, 0, 9);
cout << "排序后:" << endl;
for (i = 0; i<10; i++) {
cout << a[i] << " ";
}
cout << endl;
system("Pause");
return 0;
}