分區並具有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。這只是一個基本的快速排序,由於某種原因我有麻煩。
謝謝。還有一個問題。這需要多長時間才能運行?因爲目前需要15-20秒。如果我用cpp.sh即時運行它,但如果我使用視覺工作室,則需要更長的時間。 –
@NickPeterson它不應該花很長時間。你只是排序了一百個元素。如果你真的推動自己,你可以在15-20秒內手動*。您的IDE可能會因爲調試和內存需求而彎腰。 [在這裏查看簡化運行,排序一百萬個插槽](http://ideone.com/VCbBc0)。祝你好運。 – WhozCraig
抱歉,我忘記提及我使用了500萬個元素。 –