快速排序

来源:互联网 发布:集合和数组的优缺点 编辑:程序博客网 时间:2024/05/24 06:47

今天把快排写了下,先介绍下,快排,常用排序方法,最差情况下n方,最好情况下O(nlgn)。分治思想,利用某个值对数组进行分割,持续分割为多个数组,直到有序。

例如,原始为 1 3 7 5 4 9 6. 以6为中轴数字,分割之后为1 3 5 4 6  9 7。

分割函数维护两个集合,大于中轴数字的和小于中轴数字的。如下图所示:


代码如下:

// quick_sort.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include<iostream>#include<stdio.h>#define MAXLENTH 10000void swap(int &x,int &y){int temp;temp = x;x = y;y = temp;}int patition(int array_sort[],int start,int end){int i=start - 1,temp;temp = array_sort[end];for(int j = start;j < end;j++){if(array_sort[j] < temp){i++;swap(array_sort[i],array_sort[j]);}}swap(array_sort[i+1],array_sort[end]);return i+1;}void quick_sort(int array_sort[],int start,int end){if(start < end){int p = patition(array_sort,start,end);quick_sort(array_sort,start,p-1);quick_sort(array_sort,p+1,end);}}int _tmain(int argc, _TCHAR* argv[]){int array_sort[MAXLENTH];printf("please enter the length of the array\n");scanf("%d",&array_sort[0]);int i;printf("please enter the array\n");for(i = 1;i <= array_sort[0];i++)scanf("%d",&array_sort[i]);quick_sort(array_sort,1,array_sort[0]);for(i = 1;i <= array_sort[0];i++)printf("%d ",array_sort[i]);system("pause");return 0;}


原创粉丝点击