1 #include <ctime> 2 #include <iostream> 3 using namespace std; 4 5 template <class Type> 6 void Swap(Type &x,Type &y); 7 8 inline int Random(int x, int y); 9 10 template <class Type> 11 void BubbleSort(Type a[],int p,int r); 12 13 template <class Type> 14 int Partition(Type a[],int p,int r,Type x); 15 16 template <class Type> 17 Type Select(Type a[],int p,int r,int k); 18 19 void main() 20 { 21 //初始化数组 22 int a[100]; 23 24 //必须放在循环体外面 25 srand((unsigned)time(0)); 26 27 for(int i=0; i<100; i++) 28 { 29 a[i] = Random(0,100); 30 cout<<"a["<<i<<"]:"<<a[i]<<" "; 31 } 32 cout<<endl; 33 34 cout<<"第23小元素是"<<Select(a,0,99,23)<<endl; 35 36 37 //重新排序,对比结果 38 BubbleSort(a,0,99); 39 for(i=0; i<100; i++) 40 { 41 cout<<"a["<<i<<"]:"<<a[i]<<" "; 42 } 43 cout<<endl; 44 } 45 46 template <class Type> 47 void Swap(Type &x,Type &y) 48 { 49 Type temp = x; 50 x = y; 51 y = temp; 52 } 53 54 inline int Random(int x, int y) 55 { 56 int ran_num = rand() % (y - x) + x; 57 return ran_num; 58 } 59 60 //冒泡排序 61 template <class Type> 62 void BubbleSort(Type a[],int p,int r) 63 { 64 //记录一次遍历中是否有元素的交换 65 bool exchange; 66 for(int i=p; i<r;i++) 67 { 68 exchange = false ; 69 for(int j=0; j<=r-i; j++) 70 { 71 if(a[j]<a[j-1]) 72 { 73 Swap(a[j],a[j-1]); 74 exchange = true; 75 } 76 } 77 //如果这次遍历没有元素的交换,那么排序结束 78 if(false == exchange) 79 { 80 break ; 81 } 82 } 83 } 84 85 template <class Type> 86 int Partition(Type a[],int p,int r,Type x) 87 { 88 int i = p-1,j = r + 1; 89 90 while(true) 91 { 92 while(a[++i]<x && i<r); 93 while(a[--j]>x); 94 if(i>=j) 95 { 96 break; 97 } 98 Swap(a[i],a[j]); 99 } 100 return j; 101 } 102 103 104 template <class Type> 105 Type Select(Type a[],int p,int r,int k) 106 { 107 if(r-p<75) 108 { 109 BubbleSort(a,p,r); 110 return a[p+k-1]; 111 } 112 //(r-p-4)/5相当于n-5 113 for(int i=0; i<=(r-p-4)/5; i++) 114 { 115 //将元素每5个分成一组,分别排序,并将该组中位数与a[p+i]交换位置 116 //使所有中位数都排列在数组最左侧,以便进一步查找中位数的中位数 117 BubbleSort(a,p+5*i,p+5*i+4); 118 Swap(a[p+5*i+2],a[p+i]); 119 } 120 //找中位数的中位数 121 Type x = Select(a,p,p+(r-p-4)/5,(r-p-4)/10); 122 i = Partition(a,p,r,x); 123 int j = i-p+1; 124 if(k<=j) 125 { 126 return Select(a,p,i,k); 127 } 128 else 129 { 130 return Select(a,i+1,r,k-j); 131 } 132 }
相关文章: