快速排序算法c++实现

#include <stdio.h>
#include <stdlib.h> 
#include <time.h>
#define RANDOM_INIT()	srand(time(NULL))
#define RANDOM(L, R)	(L + rand() % ((R) - (L) + 1)) // gen a random integer in [L, R]
/**
 *  Email 956324914@qq.com
 *  Author xlf
 */

/**
 * swap 2-element, orignal value 
 */
template<typename T>
	static void swap(T &x, T &y)
	{
		T _t(x);
		x = y;
		y = _t;
	}
/**
 * the quick-sort partition routine
 */
template<typename T>
	static int partition_(T list[],int begin, int end) {
		int pivot_idx = RANDOM(begin,end);
		T pivot = list[pivot_idx];
		swap(list[begin], list[pivot_idx]);

		int i = begin + 1;
		int j = end;

		while(i <= j) {
			while((i <= end) && (list[i] <= pivot))
				i++;
			while((j >= begin) && (list[j] > pivot))
				j--;
			if(i < j)
				swap(list[i],list[j]);
		}

		swap(list[begin],list[j]);
		return j; // final pivot position
	}

/**
 * quick sort an array of range [begin, end]
 */
template<typename T>
	static void quicksort(T list[],int begin,int end) {
		if( begin < end) {
			int pivot_idx = partition_<T>(list, begin, end);
			quicksort(list, begin, pivot_idx-1);
			quicksort(list, pivot_idx+1, end);
		}
	}
	
/**
 * print all of the elements in `list` with size `n`
 */
template<typename T>
	static void printlist(T & list,int count) {
		int i;
		for(i=0;i<count;i++)
			printf("%d\t ",list[i]);
		printf("\n");
	}
	



int main()
{
	RANDOM_INIT();
	const int MAX_ELEMENTS = 10;
	int list[MAX_ELEMENTS];

	int i = 0;
	srand(time(NULL));
	// generate random numbers and fill them to the list
	for(i = 0; i < MAX_ELEMENTS; i++ ){
		list[i] = rand()%100;
	}
	printf("The list before sorting is:\n");
	printlist(list,MAX_ELEMENTS);

	// sort the list using quicksort
	quicksort(list,0,MAX_ELEMENTS-1);

	// print the result
	printf("The list after sorting using quicksort algorithm:\n");
	printlist(list,MAX_ELEMENTS);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值