c語言寫改進快速排序

1.每次以數組第一個元素爲基數​

#include <cstdio>
#include <cstdlib>
void swap(int &a,int &b)
{
	int temp;
	temp = a;
	a = b;
	b = temp;
}

int*  partition(int A[], int L, int R)
{
	int less = L - 1;
	int more = R + 1;
	int cur = L;
	int num = A[L];
	while (cur < more)
	{
		if (num>A[cur])
		{
			swap(A[less + 1], A[cur]);
			less++; cur++;
		}
		else if (num < A[cur])
		{
			swap(A[cur], A[more - 1]);
			more--;
		}
		else
		{
			cur++;
		}
	}
	return new int[] {less+1,more-1};//返回兩個邊界
}
void QuickSort(int A[], int L, int R)
{
	if (L < R)
	{
		int *p=(int*)malloc(sizeof(int)*2);
		p = partition(A, L, R);
		QuickSort(A, L, p[0]-1);
		QuickSort(A, p[1]+1, R);
	}
}
int main()
{
	int A[] = { 4, 3, 9, 2, 0, 4, 1, 6, 8, 1, 1, 1, 7 };
	for (int i = 0; i < 13; i++)
	{
		printf("%d ", A[i]);
	}
	printf("\n");
	QuickSort(A, 0, 12);
	for (int i = 0; i < 13; i++)
	{
		printf("%d ", A[i]);
	}
	printf("\n");
	system("pause");
	return 0;
}

 運行結果:

 每次以數組最後一個元素爲基數

#include <cstdio>
#include <cstdlib>
void swap(int arr[], int i, int j)
{
	int tmp = arr[i];
	arr[i] = arr[j];
	arr[j] = tmp;
}
int *partition(int arr[], int l, int r) {
	int less = l - 1;
	int more = r;//用最後一個作比較
	while (l < more) {
		if (arr[l] < arr[r]) {
			swap(arr, ++less, l++);
		}
		else if (arr[l] > arr[r]) {
			swap(arr, --more, l);//每次交換後arr位置的數還未比較因此不進行arr++
		}
		else {
			l++;
		}
	}
	swap(arr, more, r);
	return new int[] { less + 1, more };//返回兩個邊界
}

void quickSort(int arr[], int l, int r) {
	if (l < r) {
		int *p = (int*)malloc(sizeof(int)* 2);
		p = partition(arr, l, r);
		quickSort(arr, l, p[0] - 1);
		quickSort(arr, p[1] + 1, r);
	}
}

兩種快速排序都減少了相等數的比較次數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章