C++ Program for the Gnome Sort?

C++Server Side ProgrammingProgramming

Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in bubble sort.

Input: 53421
Output: 12345

Explanation

Sorting algorithm that moving an element to its proper place is accomplished by a series of swaps, as in bubble sort. It is simply requiring loops.

Example

#include <iostream>
using namespace std;
int main() {
   int temp;
   int arr[] = { 5, 3, 4, 2, 1 };
   int n=5;
   int i;
   i = 0;
   while (i < n) {
      if (i == 0 || arr[i - 1] <= arr[i])
         i++;
      else {
         temp = arr[i-1];
         arr[i - 1] = arr[i];
         arr[i] = temp;
         i = i - 1;
      }
   }
   for (i = 0;i < n;i++) {
      cout<<arr[i]<<"\t";
   }
}
raja
Published on 19-Aug-2019 11:30:27
Advertisements