C Program to Sort the Array Elements using Gnome Sort

This C Program sort the array elements using gnome sort. Gnome sort(stupid 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. It is conceptually simple, requiring no nested loops.

Here is source code of the C Program to sort array elements using gnome sort. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Sort the Array Elements using Gnome Sort
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main()
  7. {
  8.     int i, temp, ar[10], n;
  9.  
  10.     printf("\nenter the elemts number u would like to enter:");
  11.     scanf("%d", &n);
  12.     printf("\nenter the elements to be sorted through gnome sort:\n");
  13.     for (i = 0; i < n; i++)
  14.         scanf("%d", &ar[i]);
  15.     i = 0;
  16.     while (i < n)
  17.     {
  18.         if (i == 0 || ar[i - 1] <= ar[i])
  19.             i++;
  20.         else
  21.         {
  22.             temp = ar[i-1];
  23.             ar[i - 1] = ar[i];
  24.             ar[i] = temp;
  25.             i = i - 1;
  26.         }
  27.     }
  28.     for (i = 0;i < n;i++)
  29.         printf("%d\t", ar[i]);
  30. }

$ cc gnomesort.c
$ a.out
enter the elemts number u would like to enter:7
enter the elements to be sorted through gnome sort:
6
0
9
5
2
4
3
0       2       3       4       5       6       9       
 
$ a.out
enter the elemts number u would like to enter:6
enter the elements to be sorted through gnome sort:
1
2
4
5
6
7
1       2       4       5       6       7       
 
$ a.out
enter the elemts number u would like to enter:9
enter the elements to be sorted through gnome sort:
9
8
7
6
5
4
3
3
2
2       3       3       4       5       6       7       8       9

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.