2012-09-04 75 views
-1

我不知道我的代码有什么问题,但在第30行递归开始时我的程序中断,只打印出未排序的数组,并且quickSort算法从未结束。如果任何人有任何线索,为什么这个程序不能正常工作,请让我知道。先谢谢你。QuickSort算法遇到问题

#include <iostream> 
#include <time.h> 
using namespace std; 

void quickSort(int qarray[], int l, int r){ 

    int i = l, j = r; 
    int temp; 
    int pivot = qarray[(l+r)]/2; 

    //partitioning 
    while(i<=j){ 
     while(qarray[i]< pivot) 
      i++; 
     while(qarray[j] > pivot) 
      j--; 
     if(i<=j){ 

      temp = qarray[i]; 
      qarray[i] = qarray[j]; 
      qarray[j] = temp; 
      i++; 
      j--; 

     } 
     } 
    //Recursion of the quicksort algorithm 
    if(l < j){ 

     quickSort(qarray,l,j); 

    } 
    if(i < r){ 

     quickSort(qarray,i,r); 

    } 

} 

int main(){ 

    clock_t tStart = clock(); 

    int myArray[26] ={4,2,5,6,1,3,17,14,67,45,32,66,88, 
        78,69,92,93,21,25,23,71,61,59,60,30,79}; 

    for(int i=0;i < 26;i++){ 

     cout << "Unsorted: " << myArray[i] << endl; 
    } 


    quickSort(myArray,0,25); 

    for(int i=0;i < 26;i++){ 

     cout << "Sorted: " << myArray[i] << endl; 
    } 


    double seconds = clock()/double(CLK_TCK); 
    cout << "This program has been running for " << seconds << " seconds." << endl; 

    system("pause"); 
    return 0; 
} 
+0

你是用调试器完成的吗? –

+0

乍一看,该分区似乎不正确的处理枢轴,虽然我不确定。当索引相等时,分区应该继续,而'i

+0

-1 *张贴代码墙*为什么没有工作? – Drise

回答

4

错误在此行中(至少):int pivot = qarray[(l+r)]/2;

必须int pivot = qarray[(l + r)/2];

没有意义通过2.枢轴划分阵列的元素是范围中间元件,其索引是(l + r)/2

+2

没有意义将数组的元素**除以2。pivot是索引为(l + r)/ 2的范围的中间元素。 – Rost

+0

谢谢先生,确实解决了这个问题......我没有意识到犯了这个错误。非常感谢 – Nick

+0

@Rost +1感谢您提供澄清。 – Drise