[英]QuickSort with pivot the middle element not always success
我嘗試用c編寫快速排序,並旋轉數組的中間元素。
但是我的程序並不總是顯示正確的結果。
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10 /*max size of array*/
void QuickSort(int [], int, int);
int Partition(int [], int, int);
void Swap(int *,int *);
int main()
{
srand(time(NULL));
clock_t begin,end;
double time_spend;
begin = clock();
int A[SIZE];
int i;
for(i = 0; i < SIZE; i++) /*full array with numbers 1...100*/
A[i] = rand() % (100 - 1 + 1) + 1;
printf("[");
for(i = 0; i < SIZE; i++) /*print original array*/
printf("%d,",A[i]);
printf("\b]\n");
QuickSort(A,0,SIZE - 1); /*start sorting array*/
printf("\n------After Quick Sorting-----\n");
printf("\n[");
for(i = 0; i < SIZE; i++) /*print sorted array*/
printf("%d,",A[i]);
printf("\b]\n");
end = clock();
time_spend = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Elapsed: %f second\n",time_spend);
return 0;
}
/*recursive function sorting array*/
void QuickSort(int A[], int start, int end)
{
int i,q;
if(start < end)
{
q = Partition(A,start,end); /*partition array*/
QuickSort(A,start,q - 1); /*recursive first half of array*/
QuickSort(A,q + 1,end); /*recursive second half of array*/
}
}
/*function partition with pivot the middle element*/
int Partition(int A[],int start,int end)
{
int x,i,j;
x = A[(end + start) / 2];
j = start;
i = end;
while(j < i)
{
while(A[j] < x)
j++;
while(A[i] > x)
i--;
if(j < i)
{
Swap(&A[j],&A[i]);
j++;
i--;
}
}
return i;
}
/*function exchange elements*/
void Swap(int* a,int* b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
我已經嘗試更改epuals的功能分區,但是我無法解決問題。
在分區函數中,需要考慮a[j]==x
的情況和a[i]==x
。 在這種情況下,您不能只交換它們並照常進行。 在紙上仔細閱讀,您將看到錯誤。 發生這種情況的示例-考慮以下數組:1 3 4 5 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.