`
urey
  • 浏览: 24833 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论
  • carmark: 做什么都好,自己喜欢就好,我是做Unix以及C和perl相关的 ...
    混沌。
  • urey: toeo 写道我大学 也是信息与计算科学的我现在是做java  ...
    混沌。
  • toeo: 我大学 也是信息与计算科学的我现在是做java  弄web.要 ...
    混沌。

Quick Sort

J# 
阅读更多
//header in use
#include <stdio.h>
#include <tchar.h>

#include <stdlib.h>
#include <time.h>
#include <iostream>

using namespace std;
#define MAX 20

int _tmain(int argc, _TCHAR* argv[])
{
	int sortbox[MAX];
	long start, end;
	int Z = 0;
	void QuickSort(int *, int, int);
	srand(time(NULL));						//using rand() and time() to build ramdom number vector
	start = clock();
	while(Z != 1000){
		for(int i = 0; i != MAX; i++){
			sortbox[i] = rand() % 1000;
//			cout<<sortbox[i]<<' ';
		}
		QuickSort(sortbox, 0, MAX-1);
		Z++;
	}
	end = clock() - start;
	cout << endl;
	for(int i = 0; i != MAX; i++)
	{
		cout<<sortbox[i]<<' ';
	}
	cout << endl << end;
	return 0;
}

void QuickSort(int *box,int l, int r)				//
{
	int s = 0;
	int partition(int *, int, int );
	if(l<r){
		s = partition(box, l, r);
		QuickSort(box, l, s-1);
		QuickSort(box, s+1, r);
	}
	return;
}

int partition(int *box, int l, int r)
{
	int p = box[l];
	int i = l;
	int j = r + 1;
	void swap(int &, int &);							//referance! Use it carefully

	////////////////////////////////////////////////////////////////
	while(j>=i){
		do i++; while(i <= r && box[i] < p);
		do j--; while(j >=l && box[j] > p);
		swap(box[i], box[j]);
	}
	swap(box[i], box[j]);
	swap(box[l], box[j]);
	/*///////////////////////////////////////////////////////////////
	cout << endl;
	for(int i = 0; i != MAX; i++)
	{
		cout<<box[i]<<' ';
	}
	*/
	return j;
}

void swap(int &a, int &b)
{
	int tmp = a;
	a = b;
	b= tmp;
	return;
}

 

自己写的快速排序,随机生成数列循环一千次并记录时间,时间很不均匀,差别很大。本来希望实现选择前中后的中位数来进行但是出了问题,就没有写入了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics