C Program to Implement Shell Sort Algorithm

«
»
This C program sorts a given array of integer numbers using Shell Sort technique.
Shellsort, also known as Shell sort or Shell’s method, is an in-place comparison sort. It can either be seen as a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting elements far apart from each other and progressively reducing the gap between them. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange. Worst case time complexity is O(n2) and best case complexity is O(nlog(n)).

Here is the source code of the C program to sort integers using Shell Sort technique. 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 using Shell Sort technique
  3.  */
  4. #include <stdio.h>
  5. void shellsort(int arr[], int num)
  6. {
  7.     int i, j, k, tmp;
  8.     for (i = num / 2; i > 0; i = i / 2)
  9.     {
  10.         for (j = i; j < num; j++)
  11.         {
  12.             for(k = j - i; k >= 0; k = k - i)
  13.             {
  14.                 if (arr[k+i] >= arr[k])
  15.                     break;
  16.                 else
  17.                 {
  18.                     tmp = arr[k];
  19.                     arr[k] = arr[k+i];
  20.                     arr[k+i] = tmp;
  21.                 }
  22.             }
  23.         }
  24.     }
  25. }
  26. int main()
  27. {
  28.     int arr[30];
  29.     int k,  num;
  30.     printf("Enter total no. of elements : ");
  31.     scanf("%d", &num);
  32.     printf("\nEnter %d numbers: ", num);
  33.  
  34.     for (k =  0 ; k < num; k++)
  35.     {
  36.         scanf("%d", &arr[k]);
  37.     }
  38.     shellsort(arr, num);
  39.     printf("\n Sorted array is: ");
  40.     for (k = 0; k < num; k++)
  41.         printf("%d ", arr[k]);
  42.     return 0;
  43. }

advertisement
$ gcc shellsort.c -o shellsort
$ ./shellsort
 
Enter total no. of elements : 10
Enter numbers : 36 432 43 44 57 63  94 3 5 6
Sorted array is : 3 5 6 36 43 44 57 63 94 432

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement

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

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn