Please identify what type of sorting algorithm is being used in the following c+
ID: 3581453 • Letter: P
Question
Please identify what type of sorting algorithm is being used in the following c++ code snippet. Also, please explain your justification as to how you determined the type of sorting algorithm.
-
-
void stockListType::printByGainLoss()
{
sortIndicesByGainLoss.resize(getLength());
int sub = 0;
// Sorting algorithm to sort by GainLoss
numberOfIndices = 0;
double highest = -999;
int indice = 0;
for (int i = 0; i < getLength() + 1; i++)
{
highest = -999;
for (int j = 0; j < getLength(); j++)
{
if ((list[j].getGainLoss() >= highest) && not_previous_index(j))
{
highest = list[j].getGainLoss();
indice = j;
}
}
if (not_previous_index(indice))
{
numberOfIndices++;
sortIndicesByGainLoss[sub] = indice;
sub++;
}
}
Explanation / Answer
Assuming that not_previous_index(int i) tells if index is already chosen or not. It will work like selection sort as proper element is selected for each iteration.
See there are two for loops- first one is to check again and again for all elements. The second loop is what finds element. For each i the highest is set minimum and then using loop of j the element which is larger than highest and not already found is checked. This work is done by if condition. After the inner for loop of j the if condition adds the index of found element to another array. Since an element is selected for sorting this makes sense as selection sort.