值得用一首歌时间来阅读的文章

One Song,One Article!

We have already learned how to use the algorithm of quick_sort ,however ,when we want to complete something else,we need and have to turn back and rewrite the code again. Therefore, be familiar with the quick_sort's main thought and be skilled with coding are vital to everyone especially you who are programmer. So, I just want to give the code of quick_sort for you and me.

Do you want some changes?

Or just use the sort(A),sort(B),sort(blablabla);

Here I give the code which comes from the famous book---Introduction to algorithm.

Enjoy it with the background music!

 1 #include <bits/stdc++.h>
 2 #define max_size 100010
 3 int A[max_size];
 4 
 5 using namespace std;
 6 int PARTITION(int A[],int p,int r)
 7 {
 8     int x=A[r];
 9     int i=p-1;
10     for(int j=p; j<=r-1; j++)
11     {
12         if(A[j]<=x)
13         {
14             i++;
15             swap(A[i],A[j]);
16         }
17     }
18     swap(A[i+1],A[r]);
19     return i+1;
20 }
21 
22 int RANDOMIZED_PARTITION(int A[],int p,int r)
23 {
24     int i=rand()%(r-p+1)+p;
25     swap(A[r],A[i]);
26     return PARTITION(A,p,r);
27 }
28 void RANDOMIZED_QUICKSORT(int A[],int p,int r)
29 {
30     if(p<r)
31     {
32         int q=RANDOMIZED_PARTITION(A,p,r);
33         RANDOMIZED_QUICKSORT(A,p,q-1);
34         RANDOMIZED_QUICKSORT(A,q+1,r);
35     }
36 }
37 
38 int RANDOMIZED_SELECT(int A[],int p,int r,int i)
39 {
40     if(p==r)
41     {
42         return A[p];
43     }
44     int q=RANDOMIZED_PARTITION(A,p,r);
45     int k=q-p+1;
46     if(i==k) return A[q];
47     else if(i<k)
48         return RANDOMIZED_SELECT(A,p,q-1,i);
49     else return RANDOMIZED_SELECT(A,q+1,r,i-k);
50 }
51 
52 int main()//快排程序加第i顺序统计量
53 {
54     int n;
55     cout<<"请输入数组长度:"<<endl;
56     while(~scanf("%d",&n))
57     {
58         memset(A,0,sizeof(A));
59         for(int i=1; i<=n; i++)
60         {
61             scanf("%d",&A[i]);
62         }
63         cout<<"快排结果:"<<endl;
64         RANDOMIZED_QUICKSORT(A,1,n);
65         for(int i=1; i<=n; i++)
66         {
67             cout<<A[i]<<" ";
68         }
69         int t;
70         cout<<"
请输入查询次数"<<endl;
71         cin>>t;
72         while(t--)
73         {
74             int key;
75             cout<<"请输入查找第i小的数"<<endl;
76             cin>>key;
77             int result=RANDOMIZED_SELECT(A,1,n,key);
78             cout<<""<<key<<"小的数是:"<<result<<endl;
79         }
80     }
81     cout<<"Program over!"<<endl;
82     return 0;
83 }

I just learn how to add background music, there are still many bugs which are waiting to debug! Choose enjoy it or you can just turn off it.

原文地址:https://www.cnblogs.com/zpfbuaa/p/4970527.html