2014-05-18 132 views
-3

這應該是一個快速排序算法的實現。但是當我運行它時,它會一直持續下去而不顯示任何東西。我試圖找到問題,但現在太累了。請幫忙。快速排序程序不工作?

#include <stdio.h> 

void quicksort(int arr[], int pivotIndex,int right); 
int partition(int a[],int left,int right); 

int main() 
{ 
    int arr[5] = {5, 4,2, 3, 6};  
    int left = 0; 
    int right = 4; 

    quicksort(arr, left, right); 

    for (int i = 0; i < 5; i++) 
    { 
     printf("%d ", arr[i]); 
    } 
    return 0;  
} 

void quicksort(int arr[], int left,int right) 
{ 
    if (left < right) 
    { 
     int pivotNewIndex = partition(arr, left, right); 
     quicksort(arr, left, pivotNewIndex - 1); 
     quicksort(arr, pivotNewIndex + 1, right); 
    } 
} 

int partition(int a[],int left,int right) 
{ 

    int i = left; 
    int j = right; 
    int pivotIndex = left; 
    int temp; 

    while (i < j) 
    { 
     while (a[pivotIndex] <=a[j]) 
     { 
      j--; 
     } 
     if (a[pivotIndex] > a[j]) 
     { 
      temp = a[pivotIndex]; 
      a[pivotIndex] = a[j]; 
      a[j] = temp; 
      pivotIndex = j; 
     } 

     while (a[pivotIndex] <= a[j]) 
     { 
      i++; 
     } 
     if (a[pivotIndex] < a[j]) 
     { 
      temp = a[pivotIndex]; 
      a[pivotIndex] = a[j]; 
      a[j] = temp; 
      pivotIndex = i; 
     }   
    } 
    return pivotIndex; 
} 

回答

0

也許(我沒有測試)唯一的問題

應該

while (i<j && a[pivotIndex] <=a[j]) 
{ 
    j--; 
} 
if (a[pivotIndex] > a[j]) 
{ 
    temp = a[pivotIndex]; 
    a[pivotIndex] = a[j]; 
    a[j] = temp; 
    pivotIndex = j; 
} 

while (i<j && a[pivotIndex] >= a[i]) 
{ 
    i++; 
} 
if (a[pivotIndex] < a[i]) 
{ 
    temp = a[pivotIndex]; 
    a[pivotIndex] = a[i]; 
    a[i] = temp; 
    pivotIndex = i; 
} 
+0

感謝這個完美工作。 – user2279543

1

測試

if (left < right) 

將永遠是真實的,因爲你永遠不修改離開也不變量(按值傳遞他們等功能,讓你修改副本)。

你用遞歸的,從來沒有改變左/右值做這個試驗。

PS:我不知道這是否是你的程序/算法