How to implement Gnome sort in C++
Gnome sort is a variation of insertion sort, which performs sorting without any nested loops. It was first called a Stupid sort, but later, it was named Gnome sort.
Note: The algorithm of gnome sort is inspired by a Dutch garden Gnome’s sorting technique, where they sort the flowerpots by comparing two consecutive flowerpots. If the flowerpots are in order, they move forward; otherwise, they swap them backward.
The basic idea of this algorithm for sorting is to swap adjacent elements if they are not in order until the element is adjusted to its left sub-array. The sorting loop progresses if the adjacent elements are in order and move backward otherwise.
Let’s visualize the working of the gnome sort:
Algorithm
Let’s discuss the steps of the algorithm:
index := 1while index < size(array)if index == 0 or array[index] >= array[index - 1]index := index + 1elseswap array[index] and array[index - 1]index := index -1
Code
Let’s implement the code of Gnome sort in the following playground:
#include <iostream>using namespace std;void gnome_sort(int arr[], int n){int index = 1;while(index < n){if(index == 0 || arr[index] >= arr[index - 1]){index++;}else{std::swap(arr[index], arr[index-1]);index--;}}}int main() {int arr[] = {15, 13, 24, 7, 18, 3, 22, 9};int n = sizeof(arr) / sizeof(arr[0]);std::cout << "Original Array: ";for (int i = 0; i < n; ++i) {std::cout << arr[i] << " ";}gnome_sort(arr, n);std::cout << "\nSorted Array: ";for (int i = 0; i < n; ++i) {std::cout << arr[i] << " ";}return 0;}
Explanation
Let’s discuss the code below:
- Line 5: We created a variable
indexto store the current index. We initialized it with a value . - Line 7: We use a
whileloop onindexto perform sorting. This loop will iterate until the value ofindexis less than the array’s length. - Lines 8–14: We use the
if-elsecondition to implement the algorithm’s logic. We increment the value ofindexif the value of the index is zero or the array elements atindexandindex-1are in order. Otherwise, the elements are swapped, and the value ofindexis decreased. - Lines 19–24: We create an array and print it before sorting.
- Lines 26–30: We call the
gnome_sort()function and print the array after sorting.
Complexity
The time complexity of the Gnome sort algorithm is as follows:
- Best-case: The best-case time complexity of the Gnome sort is .
- Worst-case: The worst-case time complexity of the Gnome sort is .
- Average-case: The average-case time complexity of the Gnome sort is .
The Gnome sort performs the in-place sorting and requires no extra space. So, the space complexity of the Gnome sort is .
Benefits
- The Gnome sort algorithm is simple and easy to implement.
- It is a space-efficient algorithm because it requires no extra space to sort.
- It is a stable sorting algorithm that maintains the order of equal elements.
- It is an adaptive sorting algorithm that performs better on partially or nearly sorted lists.
Limitations
- The worst-case time complexity of Gnome sort is , which means it can be slow for large arrays.
- Its performance is very unpredictable, especially on larger datasets. It performs decently on some inputs and becomes extremely slow on others.
- The Gnome sort is rarely used in practice due to its poor performance compared to other efficient sorting algorithms, such as merge sort, heap sort, quick sort, etc.
How to optimize the Gnome sort
We can optimize the performance of Gnome sort by doing some tweaks to its algorithm. These changes include the following:
- Before performing the swapping steps, store the value of the
indexin a temporary variable and restore it after the element is placed into its location by swapping. This can save unnecessary variable increment steps. - Instead of comparing and swapping the element to the left subarray, we can use binary search to find the position of the element and shift elements. We can save comparisons by performing this step. It can be very useful where the comparison cost is high.
Unlock your potential: Sorting algorithms series – all in one place!
To continue your exploration of sorting algorithms, check out our series of Answers below:
What are sorting algorithms?
Understand the fundamentals of sorting algorithms and their role in organizing data efficiently.What is tree sort?
Learn how tree-based structures can be used to sort elements efficiently.What is Bitonic sort?
Discover Bitonic Sort, a parallel sorting algorithm ideal for hardware implementations.What is Flash Sort?
Explore Flash Sort, a hybrid sorting technique designed for fast performance on large datasets.How to implement the pigeonhole sorting algorithm in Python
A step-by-step guide to implementing Pigeonhole Sort in Python for efficient data sorting.How to implement comb sort in C++
Learn how to implement Comb Sort in C++ to improve sorting efficiency over Bubble Sort.Implementation of the cocktail sort in C++
Understand how Cocktail Sort refines Bubble Sort for bidirectional sorting in C++.How to implement cocktail sort in Python
Implement Cocktail Sort in Python to enhance sorting performance with a two-way pass.How to implement Gnome sort in C++
Explore the simplicity of Gnome Sort and its implementation in C++.How to implement pancake sort in Java?
Learn how to implement Pancake Sort in Java, inspired by flipping pancakes to sort stacks.Comparison of linear-time sorting algorithms
Analyze and compare different linear-time sorting algorithms to understand their efficiency.
Free Resources