Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AhmetEnesKCC/9a843232f2b14a501afce0a53a0f4186 to your computer and use it in GitHub Desktop.
Save AhmetEnesKCC/9a843232f2b14a501afce0a53a0f4186 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
void swap(int * array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
bool willMoveNext(int number, int nextNumber) {
return number > nextNumber;
}
void moveNext(int * array, int index) {
swap(array,index,index+ 1);
}
void sort_process(int * array,int array_size, int last_index_expected, int last_index_stopped) {
int i = 0;
for (i; i < last_index_expected; i ++) {
if (willMoveNext(array[i], array[i + 1])) {
moveNext(array,i);
}
else {
last_index_stopped = i + 1;
}
if (last_index_stopped == last_index_expected) {
last_index_expected = last_index_expected - 1;
}
}
if (last_index_expected > 0) {
sort_process(array, array_size, last_index_expected, last_index_stopped);
}
}
void gnome_sort(int * array, int array_size) {
int last_index_expected = array_size - 1;
int last_index_stopped = 0;
sort_process(array, array_size, last_index_expected, last_index_stopped);
}
void printArray(int * array, int array_size) {
cout << "[";
int j = 0;
for (j; j < array_size; j++) {
cout << array[j];
if (j != array_size - 1) {
cout << " , ";
}
}
cout << "]";
}
int main() {
int array[] = {12,45,98, 123,45,56,89,95,23};
int array_size = sizeof (array) / sizeof (int);
gnome_sort(array,array_size);
printArray(array,array_size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment