Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program for the Gnome Sort?
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";
}
}Advertisements