C Examples on Special Sorting Algorithms
Posted by Superadmin on July 05 2019 22:26:35

 

 

 

The C programs in this section illustrate other special Sorting Algorithms. These include Insertion Sort, Postman Sort, LSDRadix Sort, Heap Sort and Gnome Sort. Insertion Sort sorts the array by shifting the elements one by one. Postman Sort is a type of Bucket Sort in which the elements of an array are divided into buckets and then each bucket is sorted individually. LSDRadix Algorithm is used to sort the keys in integer representation order. Heap Sort is based on binary heap data structure and sorts elements similar to selection sort where the maximum element is placed at the end of the list. Gnome sort method sorts the items by comparing the current item with the previous item. If they are in order, move to the next item; If they are out of order, swap them and move to the previous item. If there is no previous item, move to the next item.

 

C Program to Implement Insertion Sort 
C Program to Implement Postman Sort Algorithm 
C Program to Sort an Integer Array using LSDRadix Sort Algorithm 
C Program to Sort an Array based on Heap Sort Algorithm 
C Program to Sort the Array Elements using Gnome Sort

 


 

C Program to Implement Insertion Sort

This is a C Program to implement Insertion Sort Algorithm.

Problem Description

We have to input an array of numbers and sort them using Insertion Sort algorithm in C Language.

Problem Solution

1. Here in order to sort an array we will be using Insertion Sort Algorithm. There are many advantages associated with an insertion sort. It is simple to implement and is quite efficient for small sets of data, especially if it is substantially sorted.

2. Another advantage associated with insertion sort is the fact that it needs only a constant amount of memory space for the whole operation. It is more efficient than other similar algorithms such as bubble sort or selection sort.

For example:

If we have the array as {40,10,50,70,30}
and we apply insertion sort to sort the array,
then the resultant array after each iteration will be as follows:

               Original array: {40, 10, 50, 70, 30}

Array after first iteration is     10 ->  40    ->  50   ->   70   ->   30
Array after second iteration is    10 ->  40    ->  50   ->   70   ->   30
Array after third iteration is     10 ->  40    ->  50   ->   70   ->   30
Array after fourth iteration is    10 ->  30    ->  40   ->   50   ->   70
            
               Sorted array is  10  30  40  50  70
Expected Input and Output

1. Average case (Unsorted array): When the input array has random distribution of numbers.

For example:

If the input array is {4, 6, 1, 2, 5, 3}
the expected output array will have data as {1, 2, 3, 4, 5, 6}

2. Best case (Sorted Array): When the input array is already sorted, in that case we have to make minimum number of swaps.

For example:

If the input array has data as {-3, 31, 66}        
then the expected output array will have data as {-3, 31, 66}

3. Worst Case (Reverse sorted array): When the array is sorted in reverse manner, in that case we have to make maximum number of swaps.

For example:

If the input array has elements as {9, 8, 6, 3, 1}
then the output array will have data as {1, 3, 6, 8, 9}
Program/Source Code

Here is source code of the C Program to sort an array of integers using Insertion Sort Algorithm. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.

advertisement
  1. /* C Program to sort an array in ascending order using Insertion Sort */
  2. #include <stdio.h>
  3. int main()
  4. {
  5.     int n, i, j, temp;
  6.     printf("Enter number of elements\n");
  7.     scanf("%d", &n);
  8.     int arr[n];
  9.     printf("Enter %d integers\n", n);
  10.     for (i = 0; i < n; i++)
  11.     {
  12.         scanf("%d", &arr[i]);
  13.     }
  14.     for (i = 1 ; i <= n - 1; i++)
  15.     {
  16. 	    j = i;
  17.             while ( j > 0 && arr[j-1] > arr[j])
  18.             {	        
  19.                 temp     = arr[j];
  20.                 arr[j]   = arr[j-1];
  21.                 arr[j-1] = temp;
  22.                 j--;
  23.             }
  24.     }
  25.     printf("Sorted list in ascending order:\n");
  26.     for (i = 0; i <= n - 1; i++)
  27.         {
  28. 	    printf("%d\n", arr[i]);
  29.         }
  30.     return 0;
  31. }
Program Explanation

1. Insertion Sort is basically insertion of an element from a random set of numbers, to its correct position where it should actually be, by shifting the other elements if required.
2. The first element in the array is considered as sorted, even if it is an unsorted array. The array is sub-divided into two parts, the first part holds the first element of the array which is considered to be sorted and second part contains all the remaining elements of array.
3. With each iteration one element from the second part is picked and inserted into the first part of array at its correct position by shifting the existing elements if required.
4. This goes until the last element in second part of array is placed in correct position in the output array.
5. In some cases Insertion Sort is considered better than selection and bubble sort because insertion sort has time complexity of O(n) in best case, while selection and bubble sort have time complexities of the order O(n^2)

Runtime Test Cases
/* Average case */
 
Enter number of elements
6
Enter 6 integers
4 6 1 2 5 3
Sorted list in ascending order:
1
2
3
4
5
6
 
/* Best case */
 
Enter number of elements
3
Enter 3 integers
-3 31 66
Sorted list in ascending order:
-3
31
66
 
/* Worst case */
 
Enter number of elements
5
Enter 5 integers
9 8 6 3 1
Sorted list in ascending order:
1
3
6
8
9

 


 

C Program to Implement Postman Sort Algorithm

This C Program implements Postman Sort Algorithm.

 

Here is source code of the C Program implements Postman Sort Algorithm. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* 
  2.  * C Program to Implement Postman Sort Algorithm
  3.  */
  4. #include <stdio.h>
  5.  
  6. void arrange(int,int);
  7. int array[100], array1[100];
  8. int i, j, temp, max, count, maxdigits = 0, c = 0;
  9.  
  10. void main()
  11. {
  12.     int t1, t2, k, t, n = 1;
  13.  
  14.     printf("Enter size of array :");
  15.     scanf("%d", &count);
  16.     printf("Enter elements into array :");
  17.     for (i = 0; i < count; i++)
  18.     {
  19.         scanf("%d", &array[i]);
  20.         array1[i] = array[i];            
  21.     }
  22.     for (i = 0; i < count; i++)
  23.     {
  24.         t = array[i];        /*first element in t */
  25.         while(t > 0)
  26.         {
  27.             c++;
  28.             t = t / 10;        /* Find MSB */
  29.         }
  30.         if (maxdigits < c) 
  31.             maxdigits = c;   /* number of digits of a each number */
  32.         c = 0;
  33.     }
  34.     while(--maxdigits) 
  35.         n = n * 10;      
  36.  
  37.     for (i = 0; i < count; i++)
  38.     {
  39.         max = array[i] / n;        /* MSB - Dividnng by perticular base */
  40.         t = i;
  41.         for (j = i + 1; j < count;j++)    
  42.         {
  43.             if (max > (array[j] / n))
  44.             {
  45.                 max = array[j] / n;   /* greatest MSB */
  46.                 t = j;
  47.             }
  48.         }
  49.         temp = array1[t];
  50.         array1[t] = array1[i];
  51.         array1[i] = temp;
  52.         temp = array[t];
  53.         array[t] = array[i];
  54.         array[i] = temp;
  55.     }
  56.     while (n >= 1)
  57.     {
  58.         for (i = 0; i < count;)
  59.         {
  60.             t1 = array[i] / n;
  61.             for (j = i + 1; t1 == (array[j] / n); j++);
  62.                 arrange(i, j);
  63.             i = j;
  64.         }
  65.         n = n / 10;
  66.     }
  67.     printf("\nSorted Array (Postman sort) :");    
  68.     for (i = 0; i < count; i++)
  69.         printf("%d ", array1[i]);
  70.     printf("\n");
  71. }
  72.  
  73. /* Function to arrange the of sequence having same base */
  74. void arrange(int k,int n)
  75. {
  76.     for (i = k; i < n - 1; i++)
  77.     {
  78.         for (j = i + 1; j < n; j++)
  79.         {
  80.             if (array1[i] > array1[j])
  81.             {
  82.                 temp = array1[i];
  83.                 array1[i] = array1[j];
  84.                 array1[j] = temp;
  85.                 temp = (array[i] % 10);
  86.                 array[i] = (array[j] % 10);
  87.                 array[j] = temp;
  88.             }
  89.         }
  90.     }
  91. }

 

$ cc postman.c
$ a.out
/* Average case */
 
Enter size of array :8
Enter elements into array :170
45
90
75
802
24
2
66
 
Sorted Array (Postman sort) :2 24 45 66 75 90 170 802 
 
$ a.out
/* Best case */
Enter size of array :7
Enter elements into array :25
64
185
136
36
3645
45
 
Sorted Array (Postman sort) :25 36 45 64 136 185 3645 
 
$ a.out
/* Worst case */
Enter size of array :8
Enter elements into array :15
214
166
0836
98
6254
73
642
 
Sorted Array (Postman sort) :15 73 98 166 214 642 836 6254

 


 

C Program to Sort an Integer Array using LSDRadix Sort Algorithm

This C Program sorts an integer array using lsdradix sort algorithm.

 

Here is source code of the C Program to sort an integer array using lsdradix sort algorithm. 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 an Integer Array using LSDRadix Sort Algorithm
  3.  */
  4. #include <stdio.h>
  5.  
  6. int min = 0, count = 0, array[100] = {0}, array1[100] = {0};
  7.  
  8. void main()
  9. {
  10.     int k, i, j, temp, t, n;
  11.  
  12.     printf("Enter size of array :");
  13.     scanf("%d", &count);
  14.     printf("Enter elements into array :");
  15.     for (i = 0; i < count; i++)
  16.     {
  17.         scanf("%d", &array[i]);
  18.         array1[i] = array[i];
  19.     }
  20.     for (k = 0; k < 3; k++)
  21.     {    
  22.         for (i = 0; i < count; i++)
  23.         {
  24.             min = array[i] % 10;        /* To find minimum lsd */
  25.             t = i;
  26.             for (j = i + 1; j < count; j++)    
  27.             {
  28.                 if (min > (array[j] % 10))
  29.                 {
  30.                     min = array[j] % 10; 
  31.                     t = j;
  32.                 }
  33.             }
  34.             temp = array1[t];
  35.             array1[t] = array1[i];
  36.             array1[i] = temp;
  37.             temp = array[t];
  38.             array[t] = array[i];
  39.             array[i] = temp;
  40.  
  41.         }
  42.         for (j = 0; j < count; j++)        /*to find MSB */
  43.             array[j] = array[j] / 10;
  44.     }
  45.     printf("Sorted Array (lSdradix sort) : ");
  46.     for (i = 0; i < count; i++)
  47.         printf("%d ", array1[i]);
  48. }

 

$ cc lsdradix.c
$ a.out
/* Average Case */
Enter size of array :7
Enter elements into array :170    
45 
90
75
802
24
2
Sorted Array (ladradix sort) : 2 24 45 75 90 170 802 
 
$ a.out
/*Best case */
Enter size of array :7    
Enter elements into array :22
64
121
78
159
206
348
Sorted Array (ladradix sort) : 22 64 78 159 121 206 348
 
$ a.out
/* Worst case */
Enter size of array :7
Enter elements into array :985
27
64
129
345
325
091
Sorted Array (ladradix sort) : 27 64 91 129 325 345 985


C Program to Sort an Array based on Heap Sort Algorithm

This C Program sorts an array based on heap sort algorithm.

 

Here is source code of the C Program to sort an array based on heap sort algorithm. 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 an array based on heap sort algorithm(MAX heap)
  3.  */ 
  4. #include <stdio.h>
  5.  
  6. void main()
  7. {
  8.     int heap[10], no, i, j, c, root, temp;
  9.  
  10.     printf("\n Enter no of elements :");
  11.     scanf("%d", &no);
  12.     printf("\n Enter the nos : ");
  13.     for (i = 0; i < no; i++)
  14.        scanf("%d", &heap[i]);
  15.     for (i = 1; i < no; i++)
  16.     {
  17.         c = i;
  18.         do
  19.         {
  20.             root = (c - 1) / 2;             
  21.             if (heap[root] < heap[c])   /* to create MAX heap array */
  22.             {
  23.                 temp = heap[root];
  24.                 heap[root] = heap[c];
  25.                 heap[c] = temp;
  26.             }
  27.             c = root;
  28.         } while (c != 0);
  29.     }
  30.  
  31.     printf("Heap array : ");
  32.     for (i = 0; i < no; i++)
  33.         printf("%d\t ", heap[i]);
  34.     for (j = no - 1; j >= 0; j--)
  35.     {
  36.         temp = heap[0];
  37.         heap[0] = heap[j    /* swap max element with rightmost leaf element */
  38.         heap[j] = temp;
  39.         root = 0;
  40.         do 
  41.         {
  42.             c = 2 * root + 1;    /* left node of root element */
  43.             if ((heap[c] < heap[c + 1]) && c < j-1)
  44.                 c++;
  45.             if (heap[root]<heap[c] && c<j)    /* again rearrange to max heap array */
  46.             {
  47.                 temp = heap[root];
  48.                 heap[root] = heap[c];
  49.                 heap[c] = temp;
  50.             }
  51.             root = c;
  52.         } while (c < j);
  53.     } 
  54.     printf("\n The sorted array is : ");
  55.     for (i = 0; i < no; i++)
  56.        printf("\t %d", heap[i]);
  57.     printf("\n Complexity : \n Best case = Avg case = Worst case = O(n logn) \n");
  58. }

 

$ cc heap.c
$ a.out
Average case 
Enter no of elements :7
 
Enter the nos : 6
5
3
1
8
7
2
Heap array : 8   6       7       1       5       3       2
The sorted array is :      1     2     3     5     6     7     8
Complexity : 
Best case = Avg case = Worst case = O(n logn) 
 
$ a.out
/* Best case 
Enter no of elements :7
 
Enter the nos : 12
10
8
9
7
4
2
Heap array : 12  10      8       9       7       4       2
The sorted array is :      2     4     7     8     9     10     12
Complexity : 
Best case = Avg case = Worst case = O(n logn) 
 
$ a.out
/* Worst case 
Enter no of elements :7
 
Enter the nos : 5
7
12
6
9
10
14
Heap array : 14  9    12      5       6       7       10
The sorted array is :  5     6     7     9     10     12     14
Complexity : 
Best case = Avg case = Worst case = O(n logn) 
*/

 


 

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