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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
2 3 12 34 54
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
2 3 12 34 54
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Insertion-sort distant elements first, then reduce the gap until it becomes one.
- 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.
