MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / sort

Function sort

Exercises/Modules/Chapter 08/Soln8_06.cpp:96–117  ·  view source on GitHub ↗

Recursive helper function to sort numbers in ascending sequence Numbers to be sorted are from words[start] to words[end]

Source from the content-addressed store, hash-verified

94// Recursive helper function to sort numbers in ascending sequence
95// Numbers to be sorted are from words[start] to words[end]
96void sort(std::vector<unsigned>& numbers, size_t start, size_t end)
97{
98 // start index must be less than end index for 2 or more elements
99 if (!(start < end))
100 return;
101
102 // Choose middle of the [start, end] range to partition
103 swap(numbers, start, (start + end) / 2); // Swap middle number with start
104
105 // Check values against chosen word
106 size_t current{ start };
107 for (size_t i{ start + 1 }; i <= end; i++)
108 {
109 if (numbers[i] < numbers[start]) // Is word less than chosen value?
110 swap(numbers, ++current, i); // Yes, so swap to the left
111 }
112
113 swap(numbers, start, current); // Swap the chosen value with the last swapped number
114
115 if (current > start) sort(numbers, start, current - 1); // Sort left subset if exists
116 if (end > current + 1) sort(numbers, current + 1, end); // Sort right subset if exists
117}
118
119// Sort numbers in ascending sequence
120void sort(std::vector<unsigned>& numbers)

Callers 4

mainFunction · 0.70
mainFunction · 0.50
mainFunction · 0.50
mainFunction · 0.50

Calls 3

swapFunction · 0.70
emptyMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected