ADVANCED DATA STRUCTURES PROGRAM • LEVEL 12 — ADVANCED SORTING

Sort a Power-of-Two Array with Bitonic Sort

Learn how to sort a power-of-two array with bitonic 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 5 6 7 8

COMPLETE C PROGRAM

Complete C implementation

ads-bitonic-sort-network.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' : ' '); }
void compare(int values[], int first, int second, int ascending) { if (ascending == (values[first] > values[second])) { int t = values[first]; values[first] = values[second]; values[second] = t; } }
void merge_bitonic(int values[], int low, int count, int ascending) { if (count > 1) { int half = count / 2; for (int i = low; i < low + half; i++) compare(values, i, i + half, ascending); merge_bitonic(values, low, half, ascending); merge_bitonic(values, low + half, half, ascending); } }
void bitonic_sort(int values[], int low, int count, int ascending) { if (count > 1) { int half = count / 2; bitonic_sort(values, low, half, 1); bitonic_sort(values, low + half, half, 0); merge_bitonic(values, low, count, ascending); } }

int main(void)
{
    int values[] = {3, 7, 4, 8, 6, 2, 1, 5};
    bitonic_sort(values, 0, 8, 1);
    print_values(values, 8); 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 5 6 7 8
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Build ascending and descending bitonic halves, then merge them with a fixed comparison network.
  3. Display the computed result.

Build ascending and descending bitonic halves, then merge them with a fixed comparison network.

EFFICIENCY

Time and space complexity

Time complexity

O(n log^2 n)

Auxiliary space

O(log n)

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.