C++ Gnome sort algorithm Exercise: Sort an array of elements using the Gnome sort algorithm
C++ Sorting: Exercise-7 with Solution
Write a C++ program to sort an array of elements using the Gnome sort algorithm.
Sample Solution:
C++ Code :
//Ref: https://bit.ly/2rcvXK5
#include <algorithm>
#include <iterator>
#include <iostream>
template<typename RandomAccessIterator>
void gnome_sort(RandomAccessIterator begin, RandomAccessIterator end) {
auto i = begin + 1;
auto j = begin + 2;
while (i < end) {
if (!(*i < *(i - 1))) {
i = j;
++j;
} else {
std::iter_swap(i - 1, i);
--i;
if (i == begin) {
i = j;
++j;
}
}
}
}
int main() {
int a[] = {125, 0, 695, 3, -256, -5, 214, 44, 55};
std::cout << "Original numbers:\n";
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
gnome_sort(std::begin(a), std::end(a));
std::cout << "Sorted numbers:\n";
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
Sample Output:
Original numbers: 125 0 695 3 -256 -5 214 44 55 Sorted numbers: -256 -5 0 3 44 55 125 214 695
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to sort an array of elements using the Counting sort algorithm.
Next: Write a C++ program to sort an array of elements using the Heapsort sort algorithm.
What is the difficulty level of this exercise?