\$\begingroup\$
\$\endgroup\$
I was wondering if this implementation of bubble sort could be improved. Are there any things that I have done wrong?
template<typename Element>
void bubble_sort(Element arr[], size_t size) {
auto sorted_elements = 1u;
bool sorted = false;
while (!sorted) {
sorted = true;
for (auto index = 0u; index < size - sorted_elements; ++index) {
if (arr[index] > arr[index + 1]) {
auto temp = arr[index + 1];
arr[index + 1] = arr[index];
arr[index] = temp;
sorted = false;
}
}
++sorted_elements;
}
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
Implementation
size - sorted_elements
might not return what you expect ifsize == 0
(it returnsstd::numeric_limits<unsigned int>::max()
). This makes the intended check fail forsize == 0
. This can be fixed by changing the while loops condition tosorted_elements < size && !sorted
.- You could use
std::swap(arr[index], arr[index + 1]);
to swap the elements. This way, the preferred assignment operation (copy or move) forElement
will be used (ifElement
provides its own specialization). Currently, you always copy, which might not always be preferred (e.g. with largestd::string
s).
answered Nov 14, 2017 at 11:21
-
\$\begingroup\$ Yes you are right I get a runtime error if the size is 0. I did not think about it. Thanks! \$\endgroup\$puls99– puls992017年11月14日 12:02:42 +00:00Commented Nov 14, 2017 at 12:02
-
1\$\begingroup\$ @puls99: unsigned and floating point comparisons are always suspect and should be double checked. There are many subtle bugs hidden this way \$\endgroup\$hoffmale– hoffmale2017年11月14日 12:33:15 +00:00Commented Nov 14, 2017 at 12:33
lang-cpp