快速排序

//插入排序
void InsertionSort(int a[], int n)
{
	int i, j, t;
	for(i = 1; i < n; i++)
	{
		t = a[i];
		for(j = i; j > 0 && a[j - 1] > t; j--)
			a[j] = a[j - 1];
		a[j] = t;
	}
}

template <typename T>
void swap(T *x, T *y)
{
	T temp; temp = *x;
	*x = *y; *y = temp;
}

//三数中值分割方法
int Median3(int a[], int l, int r)
{
	int c = (l + r) / 2;
	if(a[l] > a[c]) swap(&a[l], &a[c]);
	if(a[l] > a[r]) swap(&a[l], &a[r]);
	if(a[c] > a[r]) swap(&a[c], &a[r]);
	swap(&a[c], &a[r - 1]);
	return a[r - 1];
}

//快速排序主例程
void Qsort(int a[], int l, int r)
{
	int i, j, p;
	if(l + 3 <= r)
	{
		p = Median3(a, l, r);
		i = l; j = r - 1;
		for(;;)
		{
			while(a[++i] < p){}
			while(a[--j] > p){}
			if(i < j) swap(&a[i], &a[j]);
			else break;
		}
		swap(&a[i], &a[r - 1]);
		Qsort(a, l, i - 1);
		Qsort(a, i + 1, r);
	}
	else
		InsertionSort(a + l, r - l + 1);
}

  

posted @ 2013-01-18 11:23  ChobitsSP  阅读(148)  评论(0)    收藏  举报