2014-05-18 5 views
-3

이것은 퀵 정렬 알고리즘의 구현으로 간주됩니다. 그러나 그것을 실행할 때 아무 것도 표시하지 않고 영원히 계속됩니다. 문제를 찾으려고했지만 너무 피곤합니다. 도와주세요.quicksort 프로그램이 작동하지 않습니까?

#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) 

당신이 이 (당신이 사본을 수정 있도록, 다른 함수에 값으로 전달할)바로 변수를 왼쪽으로 수정하지 않습니다 때문에 항상 true가됩니다.

변경하지 않는 왼쪽/오른쪽 값으로이 테스트를 반복적으로 수행하고 있습니다.

PS : 나는이 프로그램/알고리즘 아마

관련 문제