刚完成了一篇博客,讲述的是快速排序,哈哈,研究明白了用起来还是挺爽的
-
题目描述:
-
浙江桐乡乌镇共有n个人,请找出该镇上的前m个大富翁.
-
输入:
-
输入包含多组测试用例.
每个用例首先包含2个整数n(0<n<=100000)和m(0<m<=10),其中: n为镇上的人数,m为需要找出的大富翁数, 接下来一行输入镇上n个人的财富值.
n和m同时为0时表示输入结束.
-
输出:
-
请输出乌镇前m个大富翁的财产数,财产多的排前面,如果大富翁不足m个,则全部输出,每组输出占一行.
-
样例输入:
-
3 1 2 5 -1 5 3 1 2 3 4 5 0 0
-
样例输出:
-
5 5 4 3
- #include<stdio.h>
- #include<stdlib.h>
- voidquicksort(int*A,intp,intr);
- intpartition(int*A,intp,intr);
- intmain()
- {
- intn,m,i,j,temp;
- intrich[100001]={0};
- while(scanf("%d%d",&n,&m))
- {
- //终止条件
- if(m==0&&n==0)
- {
- break;
- }
- //循环接受财富赋值
- for(i=0;i<n;i++)
- {
- scanf("%d",&rich[i]);
- }
- //快速排序对财富进行从大到小排序
- quicksort(rich,0,n-1);
- //判断m和n的大小,进行输入
- if(m<=n)
- {
- for(i=0;i<m;i++)
- {
- if(i!=m-1)
- printf("%d",rich[i]);
- else
- printf("%d\n",rich[i]);
- }
- }else
- {
- for(i=0;i<n;i++)
- {
- if(i!=n-1)
- printf("%d",rich[i]);
- else
- printf("%d\n",rich[i]);
- }
- }
- }
- return0;
- }
- /**
- *Description:快速排序主流程
- */
- voidquicksort(int*A,intp,intr)
- {
- intpivot;
- if(p<r)
- {
- pivot=partition(A,p,r);
- quicksort(A,p,pivot-1);
- quicksort(A,pivot+1,r);
- }
- }
- /**
- *Description:快速排序寻找基准点
- */
- intpartition(int*A,intp,intr)
- {
- intleft=p;//从左往右扫描
- intright=r;//从右往左扫描
- intstand=A[p];//基准
- //从区间两端向中间扫描,直到left==right为止
- while(left<right)
- {
- while(left<right&&A[right]<=stand)
- {
- right--;
- }
- if(left<right)
- A[left++]=A[right];
- while(left<right&&A[left]>=stand)
- {
- left++;
- }
- if(left<right)
- A[right--]=A[left];
- }
- //基准最后的定位位置
- A[left]=stand;
- returnleft;
- }