分享

随机选择算法

 紫衣风华 2014-11-01

对于一个无序的数列,如何以线性时间选择其中位数?快速排序可以,但时间复杂度为O(nlogn),我们并不想得到整个数列的顺序,只需要其中位数,即第n/2个数。因此,我们从快速排序算法的思路得到随机选择算法,时间复杂度为o(n)

  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. #include <stdlib.h>  
  6. #include <conio.h>   
  7. #include <time.h>   
  8.   
  9. int Partition(int L[],int first,int last)  
  10. {  
  11.     int left = first;  
  12.     int right = last;  
  13.     int pivot = L[first];  
  14.       
  15.     while (left < right)  
  16.     {  
  17.         while (left < right && L[right] >= pivot)right--;  
  18.         L[left] = L[right];  
  19.         while (left < right && L[left] < pivot) left++;  
  20.         L[right] = L[left];  
  21.     }  
  22.     L[left] = pivot;  
  23.     return left;  
  24. }  
  25. int Random_Partition(int L[],int first,int last)  
  26. {  
  27.     int i;  
  28.     int temp;  
  29.       
  30.     srand((unsigned)time(NULL));  
  31.     i = rand() % (last - first + 1)+first;  
  32.       
  33.     temp = L[i];  
  34.     L[i] = L[last];  
  35.     L[last] = temp;  
  36.     return Partition(L,first,last);  
  37. }  
  38. int RandomizeSelect(int L[],int first,int last,int mid_num)  
  39. {  
  40.     int q,k;  
  41.       
  42.     if(first == last)return L[first];  
  43.       
  44.     q = Random_Partition(L,first,last);  
  45.     k = q - first + 1;  
  46.       
  47.     if (mid_num == k)return L[q];  
  48.     else if (mid_num < k)return RandomizeSelect(L,first,q - 1,mid_num);  
  49.     else return RandomizeSelect(L,q + 1,last,mid_num - k);  
  50. }  
  51.   
  52.   
  53. void main()  
  54. {  
  55.     int L[8] = {3,45,13,27,34,23,56,8};  
  56.     int select;  
  57.   
  58.     select = RandomizeSelect(L,0,7,1);  
  59.     cout<<select<<endl;  
  60.     select = RandomizeSelect(L,0,7,2);  
  61.     cout<<select<<endl;  
  62.     select = RandomizeSelect(L,0,7,3);  
  63.     cout<<select<<endl;  
  64.     select = RandomizeSelect(L,0,7,4);  
  65.     cout<<select<<endl;  
  66.       
  67.     select = RandomizeSelect(L,0,7,5);  
  68.     cout<<select<<endl;  
  69.     select = RandomizeSelect(L,0,7,6);  
  70.     cout<<select<<endl;  
  71.     select = RandomizeSelect(L,0,7,7);  
  72.     cout<<select<<endl;  
  73.     select = RandomizeSelect(L,0,7,8);  
  74.     cout<<select<<endl;  
  75. }  


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多