Chinaunix首页 | 论坛 | 博客
  • 博客访问: 42586
  • 博文数量: 20
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 200
  • 用 户 组: 普通用户
  • 注册时间: 2015-11-05 10:35
文章分类

全部博文(20)

文章存档

2016年(16)

2015年(4)

我的朋友

分类: C/C++

2016-04-14 10:09:29

快速排序:是冒泡排序的一种改进

主要思想:找到一个基准,从后往前找比基准小的,都将它放到左边,从前往后找比基准大的都放到右边,这样就将数组分为两部分,并且左边的都比右边的大,然后进行递归操作。

C语言代码:

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #define MAX 225

  3. int R[MAX];
  4. //快速排序,递归函数
  5. int Partition(int i,int j)
  6. {
  7.     int privot=R[i]; //让基准等于左侧第一个数字
  8.     while(i<j)
  9.     {
  10.         while(i<j&&R[j]>=privot)
  11.         j--;    //从右向左找比基准小的
  12.         if(i<j)
  13.         R[i++]=R[j];
  14.         while(i<j&&R[i]<=privot)
  15.         i++;    //从左向右找比基准大的
  16.         if(i<j)
  17.         R[j--]=R[i];
  18.      }
  19.      R[i]=privot;
  20.     return i;
  21.  }
  22.  
  23.  void Quick_Sort(int low,int high)
  24.  {
  25.      if(low<high)
  26.      {
  27.          int p=Partition(low,high);
  28.          Quick_Sort(low,p-1);
  29.          Quick_Sort(p+1,high);
  30.      }
  31.  }
  32.  
  33.  int main()
  34.  {
  35.      int i,n;
  36.      printf("快速排序示例:\n");
  37.      printf("Please input the n above 1 and below %d\n",MAX);
  38.      scanf("%d",&n);
  39.      if(n<1||n>MAX)
  40.      {
  41.          printf("Please input right n!");
  42.          return 0;
  43.      }
  44.      printf("Please input the array under n one by one:\n");
  45.      for(i=1;i<=n;i++)
  46.      {
  47.          scanf("%d",&R[i]);
  48.      }
  49.      printf("The array you input is:\n");
  50.      for(i=1;i<=n;i++)
  51.      {
  52.          printf("%d ",R[i]);
  53.      }
  54.      Quick_Sort(1,n);
  55.      printf("The array after Quick_Sort is:\n");
  56.      for(i=1;i<=n;i++)
  57.      {
  58.          printf("%d ",R[i]);
  59.      }
  60.      return 0;
  61.  }

阅读(1306) | 评论(0) | 转发(0) |
0

上一篇:希尔排序

下一篇:直接选择排序

给主人留下些什么吧!~~