Simple Shell Sort Program in C
On this page (5sections)
About this program
This is an example program in c sorting programs. Read the concept first: C Array, then study the code and output below.
Definition
Shellsort, also known as Shell sort or Shell’s method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange or sorting by insertion. The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared.
Simple Shell Sort Program Example
/* Simple Shell Sort Program Using Array in C*/
/* Data Structure Programs,C Array Examples */
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 5
int main() {
int arr_sort[MAX_SIZE], i, j, k, a, t;
printf("Simple Shell Sort Example - Functions and Array\n");
printf("\nEnter %d Elements for Sorting\n", MAX_SIZE);
for (i = 0; i < MAX_SIZE; i++)
scanf("%d", &arr_sort[i]);
printf("\nYour Data :");
for (i = 0; i < MAX_SIZE; i++) {
printf("\t%d", arr_sort[i]);
}
for (i = MAX_SIZE / 2; i > 0; i = i / 2) {
for (j = i; j < MAX_SIZE; j++) {
for (k = j - i; k >= 0; k = k - i) {
if (arr_sort[k + i] >= arr_sort[k])
break;
else {
//Swapping Values
t = arr_sort[k];
arr_sort[k] = arr_sort[k + i];
arr_sort[k + i] = t;
}
}
printf("\nShell Sort Iteration [%d:%d] ", i, j);
for (a = 0; a < MAX_SIZE; a++) {
printf("\t%d", arr_sort[a]);
}
}
}
printf("\n\nSorted Data :");
for (i = 0; i < MAX_SIZE; i++) {
printf("\t%d", arr_sort[i]);
}
getch();
}
Sample Output:
Simple Shell Sort Example - Functions and Array
Enter 5 Elements for Sorting
4556
300
201
10
23
Your Data : 4556 300 201 10 23
Shell Sort Iteration [2:2] 201 300 4556 10 23
Shell Sort Iteration [2:3] 201 10 4556 300 23
Shell Sort Iteration [2:4] 23 10 201 300 4556
Shell Sort Iteration [1:1] 10 23 201 300 4556
Shell Sort Iteration [1:2] 10 23 201 300 4556
Shell Sort Iteration [1:3] 10 23 201 300 4556
Shell Sort Iteration [1:4] 10 23 201 300 4556
Sorted Data : 10 23 201 300 4556
Related Pages
Learn the concept first, then study the code:
- Data Structures — Browse all Data Structures.
- C Array — Concept — sorting operates on array elements.
- Simple Bubble Sort Program in C — More in c sorting programs.
- Simple Bubble Sort Program using functions in C — More in c sorting programs.