zoukankan      html  css  js  c++  java
  • 快速排序 分类: 算法 2014-10-10 11:05 541人阅读 评论(0) 收藏

    快速排序是基于分治思想的排序,以递增排序为例:
    首先选取一个基准元素pivot,将小于pivot的元素移到其左侧,
    大于pivot的元素移到其右侧。这一轮固定了pivot的位置。
    然后对其左右两侧执行相同的操作。
    快速排序平均时间复杂度O(nlogn),最差时间复杂度O(n^2);空间复杂度O(1)。

    示例代码如下:

    #include<stdio.h>
    #define Elemtype int
    int  partion(Elemtype A[],int low,int high)
    {
    	Elemtype pivot=A[low];
    	while(low<high)
    	{
    		while(low<high&&A[high]>=pivot)high--;
    		A[low]=A[high];
    		while(low<high&&A[low]<=pivot)low++;
    		A[high]=A[low];
    	}
    	A[low]=pivot;
    	return low;
    }
    void quicksort(int A[],int low,int high)
    {
    	if(low<high)
    	{
    		int pivotpos=partion(A,low,high);
    		quicksort(A,low,pivotpos-1);
    		quicksort(A,pivotpos+1,high);
    	}
    }
    int main()
    {
    	int A[12]={12,3,4,5,6,77,4,22,22,3,5,7};
    	quicksort(A,0,11);
    	for(int i=0;i<12;i++)
    	{
    		printf("%d ",A[i]);
    	}
    }


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    PostgreSQL数据损坏与checksum
    go get命令无响应解决方法
    vscode离线安装插件
    windows搭建Go语言环境
    centos7安装zabbix 5.0
    搭建人生重开模拟器
    博客园增加打赏
    记一次halo报错
    VM operation inconsistent with current state
    nextcloud安装onlyoffice
  • 原文地址:https://www.cnblogs.com/luo-peng/p/4646241.html
Copyright © 2011-2022 走看看