用快速排序的思想求第K大的数值

来源:互联网 发布:python msi下载 编辑:程序博客网 时间:2024/05/21 12:43

以前只是知道堆排序能快速求,而不知道快速排序也可以,然后今天通过快速排序实现了一下。

#include <iostream>using namespace std;template <class T>int quick2_sort(T a[],int low,int high){T temp=a[low];int pos=low;int i=low,j=high;while(i<j){while(i<j && a[j]>temp)j--;if(i<j){a[pos]=a[j];pos=j;}while(i<j && a[i]<temp)i++;if(i<j){a[pos]=a[i];pos=i;}}a[pos]=temp;return pos;}//利用快速排序的思想查找第K大的数值//第一个参数代表要查找的数组//第二个参数代表数组的长度//第三个参数代表要查找第几大的元素template <class T>T findkth(T a[],int n,int k){int low=0,high=n-1;while(1){int pos=quick2_sort(a,low,high);if(pos==n-k)return a[pos];else if(pos<n-k){low=pos+1;high=n-1;}else if(pos>n-k){high=pos-1;low=0;}}}int main(){int a[11]={78934,234,65,32,543,354,567,3412,23,547,423};cout<<findkth(a,11,4)<<endl;return 0;}


0 1
原创粉丝点击