2012-05-22 41 views
2

我正在研究一種C++ quicksort算法,它可以計算排序過程中重要操作的數量。它會正確地對100個值進行排序,但之後會陷入無限循環。任何幫助將不勝感激!C++ Quicksort Algorithm Crashing

//QuickSort.cpp

#include "QuickSort.h" 
#include <algorithm> 

using namespace std; 

QuickSort::QuickSort(int max) : SortData(max) 
{ 
    /* 
    maxSize = max; 
    theData = new long[max]; 
    */ 
    SortData::randomize(12); 

} 

QuickSort::~QuickSort(void) 
{ 

} 

_int64 QuickSort:: sort() 
{ 
    numops = 0; 
    quicksort(theData, 0, (size()-1)); 
    return(numops); 
} 

//Include counting number of operations 
void QuickSort::quicksort(long theData[], int left, int right) 
{ 
    //Default variables 

    if (size() <= 1 || left >= size() || right >= size()) return; //Bounds checking 

    if (left < right) 
    { 
     long pivot = partition(theData, left, right); 

     quicksort(theData, left, pivot-1); 
     quicksort(theData, pivot+1, right); 
    } 
} 

int QuickSort::partition(long theData[], int left, int right) 
{ 
    long pivot = theData[left]; 
    while (true) 
    { 
     while (theData[left] < pivot) left++; 
     numops ++; 

     while (theData[right] > pivot) right--; 
     numops ++; 

     if (left < right) 
     { 
      swap(theData[left], theData[right]); 
      numops+=3; 
     } 

     else 
     { 
      return right; 
     } 
    } 
} 

//QuickSort.h

#pragma once 
#include "SortData.h" 

class QuickSort : public SortData 
{ 

public: 
    QuickSort(int max = 100); 
    ~QuickSort(void); 
    _int64 sort(); 
private: 
    _int64 numops; 
    void QuickSort::quicksort(long theData[], int left, int right); 
    int partition(long theData[], int left, int right); 
}; 
+0

SortData是什麼樣的?它實際上是在構造函數中分配一個max max數組嗎? – emsr

+0

你的'分區'函數看起來好像會進入一個無限循環,如果它發現兩個元素等於主鍵(我可能會誤解,沒有仔細研究你的代碼)。如果這不是作業,只需使用'std :: partition'。 –

+0

另請注意,你的'numops'跳過了很多parition邏輯。 –

回答

4

在你的分區功能

if (left < right) 

總是正確的。因此,你可以得到無限的while(true)循環。

而且你可能在SortData.h中的size()函數中有一個問題,我們目前還看不到它。

由於數據是隨機的,因此您會在某些輸入集上不時看到問題。

輕微的修改必須幫助:

if (left <= right) { 
     if (left < right) { 
      swap(theData[left], theData[right]); 
      numops += 3; 
     } 
     left++; 
     right--; 
} 
else { 
    return right; 
} 

對不起,我仔細檢查:)

+0

那麼我會把它對立嗎? – user1411112

+0

我很確定這種情況很好,因爲意圖是「左」不斷增加,「正確」持續減少,並在遇到時停止。 –

+0

@Minging Duck:說的基本上是一樣的 –

1

partition卡住如果left < righttheData[left] == theData[right]

+0

那麼解決這個問題最簡單的方法是什麼? – user1411112

+0

@ user1411112:看看我的除了你的角落案例 –