Tsallaka zuwa abun ciki
Justice Tech School

Practice: Bubble Sort

Repeatedly swap neighbours that are out of order.

Example
#include <stdio.h>

int main(void) {
  int a[] = {5, 2, 9, 1};
  int n = 4;
  for (int i = 0; i < n - 1; i++)
    for (int j = 0; j < n - 1 - i; j++)
      if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; }
  for (int i = 0; i < n; i++) printf("%d ", a[i]);
  printf("\n");
  return 0;
}

Result

1 2 5 9 

Exercise

Compare neighbours.

if (a[j]  a[j + 1])

Quiz Test

Bubble sort compares what?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.