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

Function sort

Exercises/NoModules/Chapter 08/Soln8_06.cpp:95–116  ·  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

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