C Online Compiler
Example: Shell Sort Implementation in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Shell Sort Implementation #include <stdio.h> // Function to print an array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } // Function to perform Shell Sort void shellSort(int arr[], int n) { // Start with a large gap, then reduce the gap for (int gap = n / 2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements arr[0...gap-1] are already in gapped order // keep adding one more element until the entire array is gap sorted for (int i = gap; i < n; i += 1) { // Store arr[i] in temp and make a hole at position i int temp = arr[i]; // Shift earlier gap-sorted elements up until the correct // location for arr[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { arr[j] = arr[j - gap]; } // Put temp (the original arr[i]) in its correct location arr[j] = temp; } } } int main() { // Step 1: Define an unsorted array int arr[] = {12, 34, 54, 2, 3, 45, 67, 89, 1}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); // Step 2: Apply Shell Sort shellSort(arr, n); // Step 3: Print the sorted array printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS