ADVANCED DATA STRUCTURES PROGRAM • LEVEL 12 — ADVANCED SORTING

Sort with Shell Gap Reduction

Learn how to sort with shell gap reduction using a clear C program.

AdvancedAdvanced sortingOrdering

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
2 3 12 34 54

COMPLETE C PROGRAM

Complete C implementation

ads-shell-sort-gap-reduction.c
Open in compiler
#include <stdio.h>

void print_values(const int values[], int count) { for (int i = 0; i < count; i++) printf("%d%c", values[i], i == count - 1 ? '\n' : ' '); }

int main(void)
{
    int values[] = {12, 34, 54, 2, 3};
    for (int gap = 5 / 2; gap > 0; gap /= 2)
        for (int i = gap; i < 5; i++) {
            int value = values[i], j = i;
            while (j >= gap && values[j - gap] > value) { values[j] = values[j - gap]; j -= gap; }
            values[j] = value;
        }
    print_values(values, 5); return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

2 3 12 34 54
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Insertion-sort distant elements first, then reduce the gap until it becomes one.
  3. Display the computed result.

Insertion-sort distant elements first, then reduce the gap until it becomes one.

EFFICIENCY

Time and space complexity

Time complexity

Depends on gap sequence

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.