Chinaunix首页 | 论坛 | 博客
  • 博客访问: 478777
  • 博文数量: 144
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1190
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-08 20:16
文章分类

全部博文(144)

文章存档

2017年(1)

2015年(5)

2014年(108)

2013年(30)

我的朋友

分类: C/C++

2013-10-19 18:56:39

快速排序是对冒泡排序的一种改进。基本思想:通过一趟排序将待排序记录分割成两部分,一部分记录的关键字比另一部分的关键字小,然后继续对这两部分继续排序,达到整个有序。
通常选取第一个作为枢轴(支点),其他记录与这个值进行比较。

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #define MAXSIZE 20
  3. #define N 10
  4. typedef int KeyType;
  5. typedef char InfoType;
  6. typedef struct
  7. {
  8.     KeyType key;
  9.     InfoType otherinfo;
  10. }ReadType;
  11. typedef struct
  12. {
  13.     ReadType r[MAXSIZE+1];
  14.     int length;
  15. }Sqlist;
  16. void InitSq(Sqlist * L);
  17. void QuickSort(Sqlist *L);
  18. void main()
  19. {
  20.     Sqlist Sqlist1;
  21.     int i;
  22.     InitSq( &Sqlist1);
  23.     printf("请输入%d个数字用插入法进行排序\n",N-1);
  24.     for(i=1;i<N;i++)//第i=0位留着作为哨兵
  25.     {
  26.         scanf("%d",&Sqlist1.r[i].key);
  27.         Sqlist1.length++;
  28.     }
  29.     printf("排序前:\n");
  30.         for(i=1;i<N;i++)
  31.     {
  32.         printf("%d ",Sqlist1.r[i].key);
  33.     }

  34.     QuickSort(&Sqlist1);

  35.     printf("\n排序后:\n");
  36.     for(i=1;i<N;i++)
  37.     {
  38.         printf("%d ",Sqlist1.r[i].key);
  39.     }
  40.     system("pause");
  41. }
  42. void InitSq(Sqlist * L)
  43. {
  44.     int i;
  45.     for(i=0;i<=MAXSIZE;i++)
  46.     {
  47.         L->r[i].key=0;
  48.         L->length=0;
  49.         
  50.     }
  51. }

  52. int Partition(Sqlist *L,int low,int high)
  53. {
  54.     int pivotkey;
  55.     L->r[0]=L->r[low];//用第一个记录做枢轴记录
  56.     pivotkey=L->r[low].key;

  57.     while(low<high)
  58.     {

  59.         while((low<high)&&(L->r[high].key>=pivotkey))
  60.          --high;
  61.      L->r[low]=L->r[high];//比枢轴小的移动到低端

  62.      while((low<high)&&(L->r[low].key<=pivotkey))
  63.          ++low;
  64.      L->r[high]=L->r[low];//比枢轴大的移动到高端
  65.     }
  66.     L->r[low]=L->r[0];//把最后空的位置赋值为枢轴记录

  67.     return low;//返回枢轴位置

  68. }
  69. void QSort(Sqlist * L,int low,int high)
  70. {
  71.     int pivotloc;
  72.     if(low<high)
  73.     {
  74.         pivotloc=Partition(L,low,high);
  75.         QSort(L,low,pivotloc-1);
  76.         QSort(L,pivotloc+1,high);
  77.     }
  78. }
  79. void QuickSort(Sqlist *L)
  80. {
  81.     QSort(L,1,L->length);
  82. }

阅读(1010) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~