ADVANCED DATA STRUCTURES PROGRAM • LEVEL 12 — ADVANCED SORTING
Minimize Array Writes with Cycle Sort
Learn how to minimize array writes with cycle sort using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
1 2 3 4 8 9 10 10 Writes = 6
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[] = {1, 8, 3, 9, 10, 10, 2, 4}, writes = 0;
for (int start = 0; start < 7; start++) {
int item = values[start], position = start;
for (int i = start + 1; i < 8; i++) if (values[i] < item) position++;
if (position == start) continue;
while (item == values[position]) position++;
int temp = values[position]; values[position] = item; item = temp; writes++;
while (position != start) {
position = start;
for (int i = start + 1; i < 8; i++) if (values[i] < item) position++;
while (item == values[position]) position++;
temp = values[position]; values[position] = item; item = temp; writes++;
}
}
print_values(values, 8); printf("Writes = %d\n", writes); return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
1 2 3 4 8 9 10 10 Writes = 6
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Rotate each permutation cycle so every value is written directly to its final rank.
- Display the computed result.
Rotate each permutation cycle so every value is written directly to its final rank.
EFFICIENCY
Time and space complexity
Time complexity
O(n^2)
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.
