原文链接:https://blog.csdn.net/leaf_130/article/details/51464702
最近终于顿悟算法对编程的非凡意义,现计划写一系列的文章来总结下常用且比较重要的算法。
现在第一个要小结的就是 快速排序
- #include <stdio.h>
- int a[101],n;//定义全局变量,这两个变量需要在子函数中使用
- void quicksort(int left,int right) //快速排序算法
- {
- int i,j,t,temp;
- if(left > right)
- return;
- temp = a[left]; //temp中存的就是基准数
- i = left;
- j = right;
- while(i != j)
- {
- //顺序很重要,先从右边开始往左边找
- while(a[j] >= temp && i<j)
- j--;
- //再从左往右边找
- while(a[i] <= temp && i<j)
- i++;
- //交换两个数在数组中的位置
- if(i<j) //当哨兵i j 没有相遇时
- {
- t = a[i];
- a[i] =a[j];
- a[j] =t;
- }
- }
- a[left] = a[i];
- a[i] = temp;
- quicksort(left,i-1);//继续处理左边的
- quicksort(i+1,right);//继续处理右边的
- return;
- }
- int main()
- {
- int i,j;
- //读入数据
- scanf("%d",&n); //n就是待排序的个数
- for(i =1 ;i<=n;i++)
- scanf("%d",&a[i]);
- quicksort(1,n);//快速排序调用
- //输出排序结果
- for(i=1;i<=n;i++)
- printf("%d",a[i]);
- getchar();getchar();//用了暂停程序,便于查看程序输出的结果,也可以用system("pause")替代
- return 0;
- }