2014-05-18 131 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:我不知道这是否是你的程序/算法