2015-04-02 47 views
0

我嘗試寫在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,但我不能修復該問題。

回答

0

在您的分區功能中,您需要考慮其中a[j]==xa[i]==x的情況。在這種情況下,你不能只交換它們並照常進行。通過它在紙上,你會看到錯誤。發生這種情況的示例 - 考慮陣列:1 3 4 5 2