In this tutorial you will learn about the C Program to implement Shell sort Algorithm and its application with practical example.
C Program to implement Shell sort Algorithm
In this tutorial, we will learn to create a C program that will do Shell sort using C programming.
Prerequisites
Before starting this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C Programming.
- Creating and Using the user-defined function in C programming.
What is Shell Sort?
In every programming language, the sorting of data is a very important factor. Sorting works are done mainly with the techniques available in C Language. Many different techniques for sorting are available to work with but in this tutorial, we will focus on the Shell Sort Technique.
The Shell Sort is an evolved version of the insertion sort. Well will pick the data from an index point of array is and swap it with a faraway position index. Then data interchange between 2 locations from the array and doesn’t need to be too close to be swapped.
Program For Shell Sort
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#include <stdio.h> /* function for Shell Sort */ int shell(int x[], int no) { /* The array elements are rearranged at n/2, n/4, ..., first pass */ for (int in= no/2; in > 0; in /= 2) { for (int i = in; i < no; i += 1) { /* store values of x[i] to the variable flag and making the ith position empty */ int flag = x[i]; int j; for (j = i; j >= in && x[j - in] > flag; j -= in) x[j] = x[j - in]; // put flag (it means the x[i]) in its correct position x[j] = flag; } } return 0; } void printArray(int x[], int no) /* Printing elements of array sorted*/ { int i; for (i = 0; i < no; i++) printf("%d ", x[i]); } int main() { int x[] = { 11, 22, 34, 54, 55 }; int no = sizeof(x) / sizeof(x[0]); printf("Before sorting elements of array are - \n"); printArray(x, no); shell(x, no); printf("\nAfter applying shell sort, the elements of array are - \n"); printArray(x, no); return 0; } |
Output:-
In the above program, we have first declared and initialized a set of variables required in the program.
- no = it will hold the size of an array.
- x[]= it will hold the elements in an array.
- i= it will hold the integer value to the control array.
- j= it will hold the integer value to the control array.
After this, we make the main function for our program and define variables calling functions.
The Shell Sorting function body
The printing array function body