#include <iostream>
#include <string>
using namespace std;
//Iterates over the string array appNames displaying each application
//name in a separate line. There are appCount elements in the array
void displayAllApplicationNames(string appNames[], int appCount);
//Swaps strings in string array appNames between appIndex1 and appIndex2
void swapAppNames(int appIndex1, int appIndex2, string appNames[]);
//Splits string array appNames around a pivot index p (the pivot).
//Elements below index p are less than elements above index p.
//The function returns the pivot p
int pivot(int first, int last, string appNames[]);
//Implements the QuickSort algorithm to sort string array
//appNames between indeces first and last
void quickSort(int first, int last, string appNames[]);
void main()
{
string appNames[] =
{
"4) Pages", "2) Keynote", "3) Numbers",
"8) Word", "5) PowerPoint", "1) Excel",
"0) Documents", "6) Presentation", "7) Sheets"
};
displayAllApplicationNames(appNames, 9);
swapAppNames(3, 6, appNames);
displayAllApplicationNames(appNames, 9);
quickSort(0, 8, appNames);
displayAllApplicationNames(appNames, 9);
getchar();
}
void displayAllApplicationNames(string appNames[], int appCount)
{
for(appCount = 0; appCount <= 8; appCount++)
{
cout << "[" << appCount << "]\t"<< appNames[appCount] << endl;
}
if(appCount < 0 || appCount > 8)
{
cout << "_________" <<endl;
}
}
void swapAppNames(int appIndex1, int appIndex2, string appNames[])
{
string temp = appNames[appIndex1];
appNames[appIndex1] = appNames[appIndex2];
appNames[appIndex2] = temp;
}
int pivot(int first, int last, string appNames[])
{
int pivotIndex, mid = (first + last)/2;
swapAppNames(first, mid, appNames);
pivotIndex = first;
string pivotValue = appNames[first];
for (int i = first + 1; i <= last; i++)
{
if (appNames[i] < pivotValue)
{
pivotIndex++;
swapAppNames(pivotIndex, i, appNames);
}
swapAppNames(first, last, appNames);
return pivotIndex;
}
}
void quickSort(int first, int last, string appNames[])
{
if (first < last)
{
int p = pivot(first, last, appNames);
quickSort(first, p - 1, appNames);
quickSort(p + 1, last, appNames);
}
}
我的目標是對字符串數組「appNames」中的名稱進行排序。我給名稱添加了數字以顯示它們應該在的順序,但是當我運行該程序時,它似乎沒有正確排序。誰能告訴我我要去哪裏?快速排序算法運行不正常
我一直在看這幾天都沒有結果。
編輯:這裏的解決方案。非常感謝所有回覆的人。必須交換幾個變量的位置並在快速排序算法中進行讀取。
int pivot(int first, int last, string appNames[])
{
int pivotIndex, mid = (first + last)/2;
swapAppNames(first, mid, appNames);
pivotIndex = first;
string pivotValue = appNames[first];
for (int i = first + 1; i <= last; i++)
{
if (appNames[i] < pivotValue)
{
pivotIndex++;
swapAppNames(pivotIndex, i, appNames);
}
}
swapAppNames(pivotIndex, first, appNames);
return pivotIndex;
}
檢查你的'樞軸' - 有很多奇怪的事情。 –
我會重寫pivot函數,但在此期間,你能給我任何其他建議嗎?在這一點上,我真的沒有線索。如果不明顯,我是初學者,這是一項家庭作業。 – user3835257
我可以看到的第一件事是最後的交換和返回應該在循環外(在數據透視中)。其次,最後一個交換應該有'poivotindex'和索引你首先存儲的位置,而不是'first'和'last'。最後,我想你應該在最後一個地方存儲數據透視表,而不是在開始循環之前(因爲你對數組進行排序的方式,如果pivot是最大的元素,它將保持在第一位,而不是移動到它應該是最後的)。 –