forked from argonautica/sorting-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGnome_sort_cpp
41 lines (35 loc) · 862 Bytes
/
Gnome_sort_cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#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);
}