快速排序

排序的顺序(通过多次比较和交换来实现排序):
    1、首先设定一个分界值,通过该分界值将数组分成左右两个部分
 2、将大于分界值的数据集中到数组的右边,小于分界值的数据集中数组的左边,此时左边的各个元素都小于等于分界值,而右边部分各个元素都大于等于分界值。 
 3、然后,左右边的数据可以独立排序,对于左侧的数据又可以取分界值,将部分数据分为左右两部分,同样左边的放置较小值,右边放置较大值,右边也做类似的处理

 4、重复上面的过程,这个是递归的过程,通过递归将左侧部分排好序后再次递归排好右边的部分顺序,当左右顺序排好之后,整个数组就排好顺序。

// QuickSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include<IOSTREAM>
#include<CSTDIO>
#include<CSTDLIB>
#include<CSTRING>
#include<CTIME>

using namespace std;


#define  SIZE 100

void QuickSort(int *arr, int left, int right)
{
	int f,t;
	int rtemp,ltemp;

	ltemp = left;
	rtemp = right;

	f = arr[(left + right) / 2];		// 分界值
	while(ltemp < rtemp)
	{
		while(arr[ltemp] < f)	        // 查找左边值大于边界值
		{
			++ltemp;
		}
		while(arr[rtemp] > f)			// 查找右边值大于边界值
		{
			--rtemp;
		}
		if(ltemp <= rtemp)				// 交换数据位置
		{
			t = arr[ltemp];
			arr[ltemp] = arr[rtemp];
			arr[rtemp] = t;
			--rtemp;
			++ltemp;
		}
	}
	if (ltemp == rtemp)
	{
		ltemp ++;
	}
	if (left < rtemp)
	{
		QuickSort(arr,left,ltemp - 1);		// 递归
	}
	if (ltemp < right)
	{
		QuickSort(arr, rtemp + 1, right);
	}
}




int main(int argc, char* argv[])
{
	int array[SIZE], i;
	
	srand(time(NULL));
	for (i = 0;i < SIZE; i++)
	{
		array[i] = rand() / 10000 + 100;
	}
	
	cout<<"before sort -------------"<<endl;
	for (i = 0; i < SIZE; i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;
	QuickSort(array, 0, SIZE -1);
	
	cout<<"Sort: ------------------"<<endl;
	for (i = 0; i < SIZE; i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;
	getchar();
	return 0;
}

before sort -------------
102 101 100 102 100 100 100 102 101 101 101 101 100 100 102 103 101 101 101 101
100 100 103 102 100 100 102 102 102 102 102 101 100 102 101 103 101 100 100 102
101 101 100 101 100 102 102 101 101 101 102 103 100 102 103 101 101 101 102 100
102 100 102 102 100 101 103 101 100 102 102 102 102 102 100 103 101 101 102 100
103 103 102 100 101 100 101 102 100 101 101 101 100 100 100 102 100 100 102 103


Sort: ------------------
100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
100 100 100 100 100 100 100 100 100 100 101 101 101 101 101 101 101 101 101 101
101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101
102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102 102
102 102 102 102 102 102 102 102 102 102 103 103 103 103 103 103 103 103 103 103


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值