1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
void SelectionSort(vector<int> &anVector, int nSize, bool (*pComparison)(int, int));
bool Ascending(int nX, int nY)
{
return nY > nX;
}
bool Descending(int nX, int nY)
{
return nY < nX;
}
int main()
{
vector<int> myVector = { 3, 7, 9, 5, 6, 1, 8, 2, 4 };
SelectionSort(myVector, 9, Descending);
SelectionSort(myVector, 9, Ascending);
//SelectionSort(myVector,9) //Sorts Ascending by default
return 0;
}
void SelectionSort(vector<int> &anVector, int nSize, bool (*pComparison)(int, int))
{
for (int nStartIndex= 0; nStartIndex < nSize; nStartIndex++)
{
int nBestIndex = nStartIndex;
for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++)
{
if (pComparison(anVector[nCurrentIndex], anVector[nBestIndex]))
nBestIndex = nCurrentIndex;
}
swap(anVector[nStartIndex], anVector[nBestIndex]);
}
for (int iii=0; iii < nSize; iii++)
cout << anVector[iii] << " ";
cout << endl;
}
| |