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.

AdvancedAdvanced sortingOrdering

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

ads-cycle-sort-minimum-writes.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[] = {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;
}

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

1 2 3 4 8 9 10 10
Writes = 6
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Rotate each permutation cycle so every value is written directly to its final rank.
  3. 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.