Small Steps III — Thinking with Programs
Ordering from largest to smallest
Order values from largest to smallest.
What you will learn
Changing the comparison rule changes the order without changing the procedure. Listing larger values first is descending order.
Try it
Example · example2.cpp
void small_main()
{
Array<int> numbers = {7, 2, 9, 4, 5};
for (int i = 0; i < numbers.length(); i = i + 1)
{
int largest = i;
for (int j = i + 1; j < numbers.length(); j = j + 1)
if (numbers[j] > numbers[largest])
largest = j;
int temp = numbers[i];
numbers[i] = numbers[largest];
numbers[largest] = temp;
}
for (int i = 0; i < numbers.length(); i = i + 1)
print(numbers[i]);
}
Now find the largest remaining value. The comparison changes from < to >, and the output becomes 9, 7, 5, 4, 2.
You do not need to rebuild the whole loop to change sorting direction. Change which value is selected first.
Exercise
Modify Selection Sort to arrange values from largest to smallest.
Exercise starter · exercise2_starter.cpp
void small_main()
{
Array<int> numbers = {10, 3, 8, 1, 6};
// Sort from largest to smallest.
for (int i = 0; i < numbers.length(); i = i + 1)
print(numbers[i]);
}
Hint
Find largest instead of smallest, and change the comparison to >.
show solution
void small_main()
{
Array<int> numbers = {10, 3, 8, 1, 6};
for (int i = 0; i < numbers.length(); i = i + 1)
{
int largest = i;
for (int j = i + 1; j < numbers.length(); j = j + 1)
if (numbers[j] > numbers[largest])
largest = j;
int temp = numbers[i];
numbers[i] = numbers[largest];
numbers[largest] = temp;
}
for (int i = 0; i < numbers.length(); i = i + 1)
print(numbers[i]);
}