📜 ⬆️ ⬇️

Algorithms of sorting. Gnome Sort on C

Algorithms of sorting. They are not many, but not enough. There are often used, there is no one needed. I decided to review these algorithms in order to refresh both my memory and the memory users. And let's start with the rarely used Gnome Sort algorithm (gnome sorting).

The gnomish sorting algorithm was developed, according to the official author (Dick Grun), by dwarves who have sorted garden pots. True or not, the algorithm is very simple, especially for beginners. In fact, the algorithm compares the standing pots, if they are in the correct order, then we move to the next element of the array, if not, we rearrange them and go to the previous one. There is no previous element - we go forward, there is no next one - it means we are finished. Initially we are on the second element of the array.

We proceed to the implementation of the C. I think that with the input and output of the array, no one will have problems:
#include <stdio.h> #include <stdlib.h> size_t n = 0; //    long *arr = NULL; //   void Read() { size_t i; printf("Array size: "); scanf("%u", &n); arr = (long*)calloc(n, sizeof(long)); printf("Array: "); for (i = 0; i < n; i++) { scanf("%d", &(arr[i])); } } void Do() { //  } void Write() { size_t i; printf("Result: "); for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } void main() { Read(); Do(); Write(); } 


So, the sorting itself. At the beginning, we initialize the size_t counter i in a unit. We write a while loop with the condition i <n:
 void Do() { //  size_t i = 1; while (i < n) { } } 

Now the cycle. If we are at the beginning, we go forward (if (i == 0) i = 1;). If we are at the end, then we do not write anything, because cycle condition will work. If this element is equal to or greater than the previous one, then go ahead. In another case, swap the elements and go back.
')
Total ready program for sorting:
 #include <stdio.h> #include <stdlib.h> size_t n = 0; long *arr = NULL; void Read() { size_t i; printf("Array size: "); scanf("%u", &n); arr = (long*)calloc(n, sizeof(long)); printf("Array: "); for (i = 0; i < n; i++) { scanf("%d", &(arr[i])); } } void Do() { //  size_t i = 1; //  while (i < n/*    */) { if (i == 0) { i = 1; } if (arr[i-1] <= arr[i]) { ++i; //   } else { //   long tmp = arr[i]; arr[i] = arr[i-1]; arr[i-1] = tmp; //   --i; } } } void Write() { size_t i; printf("Result: "); for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } void main() { Read(); Do(); Write(); } 

Source: https://habr.com/ru/post/145682/


All Articles