2016-07-20 25 views
0

分區並具有myswap的基本快速排列功能。除了數組中的索引0以外,一切正常。C++快速排序索引0返回-842150451

#include<iostream> 
#include<string> 
#include<iostream> 
#include<vector> 
#include <ctime> 

using namespace std; 

//swap 
void myswap(int mya[], int a, int b) { 
int temp = mya[a]; 
mya[a] = mya[b]; 
mya[b] = temp; 
} 

//partition, returns pivot index 
int mypartition(int mya[], int first, int last) 
{ 
    int middle = ((first + last)/2); 
    int pivot = mya[middle]; 
    //swap first with middle 
    myswap(mya, first, middle); 
    //two pointers 
    int pivotindex = first; 
    //loop through the elements 
    for (int index = first + 1; index <= last; index++) { 
     if (mya[index] <= pivot) 
     { 
      pivotindex++; 
      myswap(mya, pivotindex, index); 
     } 
    } 
    //swap the pivot in its right place 
    myswap(mya, first, pivotindex); 
    return pivotindex; 
} 



void QuickSort(int mya[], int a, int b) 
{ 
    //partition 
    if (a <= b) 
    { 
     int index = mypartition(mya, a, b); 
     QuickSort(mya, a, index - 1); 
     QuickSort(mya, index + 1, b); 
    } 
} 



int main() { 
    //vector<int> mya; 
    int * mya = new int[5000000]; 
srand(time(0)); 
int i = 0; 
int last = 0; 
while(i < 100) 
{ 
    int x = (rand() + time(0)) % 5000000; 
    mya[last] = x; 
    last++; 
    i++; 
} 

clock_t startTime, endTime; 
startTime = clock(); 
QuickSort(mya, 0, last); 
endTime = clock(); 
    cout << "Sorted in " << (double)(endTime - startTime)/CLOCKS_PER_SEC  << "  seconds" << endl; 
for (int i = 0; i < 100; i++) 
{ 
    cout << mya[i] << endl; 
} 
delete[] mya; 
return 0; 

} 

遇到的問題IM是,數組被排序,但是當MYA [0]是所謂的for循環它輸出-842150451。這只是一個基本的快速排序,由於某種原因我有麻煩。

回答

1

你說錯了。

QuickSort(mya, 0, last-1); 

請記住,有last元素,這意味着它們的索引爲0..last-1。

在計算middle時,您也有潛在的溢出問題。使用(last - first + 1)/2 + first

希望這會有所幫助。

+0

謝謝。還有一個問題。這需要多長時間才能運行?因爲目前需要15-20秒。如果我用cpp.sh即時運行它,但如果我使用視覺工作室,則需要更長的時間。 –

+0

@NickPeterson它不應該花很長時間。你只是排序了一百個元素。如果你真的推動自己,你可以在15-20秒內手動*。您的IDE可能會因爲調試和內存需求而彎腰。 [在這裏查看簡化運行,排序一百萬個插槽](http://ideone.com/VCbBc0)。祝你好運。 – WhozCraig

+0

抱歉,我忘記提及我使用了500萬個元素。 –

1

整數溢出導致此問題。

int x = (rand() + time(0)) % 5000000;

這行有時兩個10位數號碼,其總和導致整數溢出。

只需修改聲明如下,你的代碼開始工作:

int x = (rand() % 5000000) + (time(0) % 5000000);

編輯:這是我發現使用Ideone執行你的代碼中的問題。進一步注意到我發現你的索引0問題實際上是由分區函數引起的。

變化for (int index = first + 1; index <= last; index++) {此行

for (int index = first + 1; index < last; index++) { //remove the equal sign

N.B:這對我來說固定您的問題。但我認爲你的void QuickSort(int mya[], int a, int b)
if (a <= b)應改爲if (a < b)

+0

這似乎沒有改變任何東西。它也發生在較小的數字上。 –

+0

@NickPeterson檢查我編輯的答案。 –

+0

我其實已經想通了。在我最後打電話的主要功能中,我應該最後打電話給他 - 1.感謝所有的幫助,我非常感謝。 –