分治法求第k小元素(vc++)


算法:

求一列数中的第k小元素,利用分治的策略进行递归求解。

首先随便指定一个数,这里我指定的是第一个数为第k小元素记为randK,将数组中其他的数与findK进行比较,比他小的放在左边,大的放在右边,如果randK左边的元素个数为k-1个,说明findK就是你所要找的元素,如果左边的元素个数>k-1,说明你要找的元素在左边的数中,继续使用相同的方法在左边的数中进行查找,如果左边的元素的个数<k-1,说明你要找的元素在右边的数中,则继续使用相同的办法在右边的数中进行查找。。。

代码:

#include<iostream.h>

#include <time.h>

#include<stdlib.h>

#define Array_max 200

         void swap(int &a,int &b){

                   int temp;

                   temp = a;

                   a = b;

                   b = temp;

         }

         void out(int a[],int n){

                   for(int i = 0;i<n;i++){

                            cout<<a[i]<<" ";

                            if(i % 8 == 0 && i != 0)

                                     cout<<endl;

                   }

                   cout<<endl;

         }

         int findP(int a[],int oP,int R){//oP是随机元素的位置开始为0oP左边,R右边

                   int randK = a[oP];//随机找一个数

                   int iL = oP + 1;

                   int iR = R;

                   while(true){

                            while(a[iL]<randK){iL++;}

                            while(a[iR]>=randK){iR--;}

                            if(iL>=iR) break;

                            swap(a[iL],a[iR]);

                            }

                   swap(a[oP],a[iR]);

                   return iR;

         }

         int findK(int a[],int oP,int n,int k){//n为要排序的元素的个数

                   int find_k;

                   int copy_k;

                   find_k = findP(a,oP,n);//指向获取元素的最小值,oP指向获取元素的最大值

                   copy_k = find_k - oP;

                   if(k == copy_k)

                            return a[find_k];

                   if(k > copy_k)

                            return findK(a,find_k + 1,n,k - copy_k-1);

                   if(k < copy_k)

                   return findK(a,oP,find_k - 1,k);

                   else return 0;

         }

          void main(){

                   int n;

                   int k;

Begin:

                   cout<<"Please input the length of your Array:";

                   cin>>n;

                   cout<<endl;

                   int *a = new int[n];

                   srand((unsigned)time(NULL)); //生成随机数

                   for(int i = 0; i<n;i++){

                            a[i] = rand()%100;

                   }

                   cout<<"The Random_Array_element is:"<<endl;

                   out(a,n);

                   cout<<"Pleae input the K:";

                   cin>>k;

                   if(k>n) goto Begin;//输入错误,重新输入

                   else

                   cout<<"The element you find now is:"<<findK(a,0,n-1,k-1)<<endl;

         }

原文地址:https://www.cnblogs.com/chaofan/p/1623320.html