【算法总结系列-1】快速排序-c语言实现 原文链接:https://blog.csdn.net/leaf_130/article/details/51464702

原文链接:https://blog.csdn.net/leaf_130/article/details/51464702

最近终于顿悟算法对编程的非凡意义,现计划写一系列的文章来总结下常用且比较重要的算法。

现在第一个要小结的就是  快速排序

[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. int a[101],n;//定义全局变量,这两个变量需要在子函数中使用  
  3.   
  4. void quicksort(int left,int right)   //快速排序算法  
  5. {  
  6.   int i,j,t,temp;          
  7.   if(left > right)  
  8.       return;  
  9.   
  10.     temp = a[left];   //temp中存的就是基准数  
  11.   i = left;  
  12.   j = right;  
  13.   while(i != j)  
  14.   {  
  15.    //顺序很重要,先从右边开始往左边找  
  16.       while(a[j] >= temp && i<j)  
  17.           j--;  
  18.       //再从左往右边找  
  19.       while(a[i] <= temp && i<j)  
  20.           i++;  
  21.       //交换两个数在数组中的位置  
  22.       if(i<j)    //当哨兵i j 没有相遇时  
  23.       {  
  24.             t = a[i];  
  25.         a[i] =a[j];  
  26.         a[j] =t;  
  27.       }  
  28.   }  
  29.   a[left] = a[i];  
  30.   a[i] = temp;  
  31.   
  32.   quicksort(left,i-1);//继续处理左边的  
  33.   quicksort(i+1,right);//继续处理右边的  
  34.   return;  
  35. }  
  36.   
  37. int main()  
  38. {  
  39.   
  40.   int i,j;  
  41.   //读入数据  
  42.   scanf("%d",&n);      //n就是待排序的个数  
  43.   for(i =1 ;i<=n;i++)  
  44.       scanf("%d",&a[i]);  
  45.   
  46.   quicksort(1,n);//快速排序调用  
  47.   //输出排序结果  
  48.   for(i=1;i<=n;i++)  
  49.       printf("%d",a[i]);  
  50.   
  51.   getchar();getchar();//用了暂停程序,便于查看程序输出的结果,也可以用system("pause")替代  
  52.   return 0;  
  53.   
  54. }  

猜你喜欢

转载自blog.csdn.net/liangjiubujiu/article/details/80346406