三種快速排序法

期待一片自己的藍天發表於2014-06-11
/*交換函式:為了提高效率,當所交換的兩個元素值不相等時,用異或運算*/
void swap(int *a, int *b)
{
	if (*a != *b){
		*a = *a^*b;
		*b = *a^*b;
		*a = *a^*b;
	}
	else{
		int temp = *a;
		*a = *b;
		*b = temp;
	}
}

/*第一種快排:只有一個長度n,每次需計算出low和high指標*/
int QuickSort_process1(int *a, int n)
{
	int low, high, temp;
	low = 0;
	high = n - 1;
	temp = a[0];
	while (low < high){
		while (low < high&&temp <= a[high])
			--high;
		if (low < high)
			a[low] = a[high];
		while (low<high&&temp>a[low])
			++low;
		if (low < high)
			a[high] = a[low];
	}
	a[high] = temp;
	return high;
}
void QuickSort1(int *a,int n)
{
	int pos;
	if (n>0){
		pos = QuickSort_process1(a, n);
		QuickSort1(a, pos);
		QuickSort1(a + pos + 1, n - pos - 1);
	}
}

/*第二種快排:有兩個指標,一個快,一個慢。快的指標找比基元素小的數,慢的指標指向比基元素小的最後一個元素*/
/*這樣,在排序結束後,整個陣列就被基元素分為了兩部分。*/
int QuickSort_process2(int *a, int n)
{
	int first, second, temp;
	first = 0;
	second = -1;
	temp = a[n - 1];
	while (first != n){
		if (a[first] < temp){
			swap(a+second+1,a+first);
			++second;
		}
		++first;
	}
	swap(a + second + 1, a + n - 1);
	return second + 1;
}

void QuickSort2(int *a, int n)
{
	int pos;
	if (n > 0){
		pos = QuickSort_process2(a,n);
		QuickSort2(a, pos);
		QuickSort2(a + pos + 1, n - pos - 1);
	}
}

/*第三種快排,比較傳統的那種,引數中有low指標和high指標*/
int QuickSort_process3(int *a, int low, int high)
{
	int l, h, temp;
	l = low;
	h = high;
	temp = a[low];
	while (l < h){
		while (l< h&&a[h] >= temp)
			--h;
		if (l < h)
			a[l] = a[h];
		while (l < h&&a[l] < temp)
			++l;
		if (l < h)
			a[h] = a[l];
	}
	a[h] = temp;
	return h;
}

void QuickSort3(int *a, int low,int high)
{
	int pos;
	if (low < high){
		pos = QuickSort_process3(a,low,high);
		QuickSort3(a,low,pos-1);
		QuickSort3(a,pos+1,high);
	}
}


相關文章