zoukankan      html  css  js  c++  java
  • 快速排序

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

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

    C语言代码:

    #include<stdio.h>
    #define MAX 225
    
    int R[MAX];
    //快速排序,递归函数
    int Partition(int i,int j)
    {
    	int privot=R[i]; //让基准等于左侧第一个数字
    	while(i<j)
    	{
    		while(i<j&&R[j]>=privot)
    		j--;	//从右向左找比基准小的 
    		if(i<j)
    		R[i++]=R[j];
    		while(i<j&&R[i]<=privot)
    		i++;	//从左向右找比基准大的 
    		if(i<j)
    		R[j--]=R[i]; 
    	 }
    	 R[i]=privot; 
    	return i;
     } 
     
     void Quick_Sort(int low,int high)
     {
     	if(low<high)
     	{
     		int p=Partition(low,high);
     		Quick_Sort(low,p-1);
     		Quick_Sort(p+1,high);
    	 }
     }
     
     int main()
     {
     	int i,n;
     	printf("快速排序示例:
    ");
     	printf("Please input the n above 1 and below %d
    ",MAX);
     	scanf("%d",&n);
    	 if(n<1||n>MAX)
    	 {
    	 	printf("Please input right n!");
    	 	return 0;
    	  } 
    	  printf("Please input the array under n one by one:
    ");
    	  for(i=1;i<=n;i++)
    	  {
    	  	scanf("%d",&R[i]);
    	  }
    	  printf("The array you input is:
    ");
    	  for(i=1;i<=n;i++)
    	  {
    	  	printf("%d ",R[i]);
    	  }
    	  Quick_Sort(1,n);
    	  printf("The array after Quick_Sort is:
    ");
    	  for(i=1;i<=n;i++)
    	  {
    	  	printf("%d ",R[i]); 
    	  }
    	  return 0;
     }
     
    

      

  • 相关阅读:
    代理模式
    组合模式
    yum配置文件详解
    责任链模式
    git看不到别人创建的远程分支
    学习gulpfile.babel.js随笔
    遍历数组的方法
    解决Error: ENOENT: no such file or directory, scandir 安装node-sass报错
    window对象
    Moment.js的一些用法
  • 原文地址:https://www.cnblogs.com/qysqys/p/5390018.html
Copyright © 2011-2022 走看看