Skip to content
Related Articles

Related Articles

Improve Article
C++ Program for Gnome Sort
  • Last Updated : 04 Dec, 2018

Algorithm Steps

  1. If you are at the start of the array then go to the right element (from arr[0] to arr[1]).
  2. If the current array element is larger or equal to the previous array element then go one step right
                   if (arr[i] >= arr[i-1])
                      i++;
  1. If the current array element is smaller than the previous array element then swap these two elements and go one step backwards
                       if (arr[i] < arr[i-1])
                       {
                           swap(arr[i], arr[i-1]);
                           i--;
                       }
  1. Repeat steps 2) and 3) till ā€˜iā€™ reaches the end of the array (i.e- ā€˜n-1ā€™)
  2. If the end of the array is reached then stop and the array is sorted.




// A C++ Program to implement Gnome Sort
#include <iostream>
using namespace std;
  
// A function to sort the algorithm using gnome sort
void gnomeSort(int arr[], int n)
{
    int index = 0;
  
    while (index < n) {
        if (index == 0)
            index++;
        if (arr[index] >= arr[index - 1])
            index++;
        else {
            swap(arr[index], arr[index - 1]);
            index--;
        }
    }
    return;
}
  
// A utility function ot print an array of size n
void printArray(int arr[], int n)
{
    cout << "Sorted sequence after Gnome sort: ";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << "\n";
}
  
// Driver program to test above functions.
int main()
{
    int arr[] = { 34, 2, 10, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    gnomeSort(arr, n);
    printArray(arr, n);
  
    return (0);
}
Output:
Sorted sequence after Gnome sort: -9 2 10 34

Please refer complete article on Gnome Sort for more details!

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :