Skip to lab content

UNIT 05 · Sorting and Searching

Bubble sort in ascending order

EXERCISE 05CC173 sample runs

THE SYLLABUS QUESTION

What you need to solve

Write a C program that implements the Bubble sort method to sort a given list of integers in ascending order.
Input format & conventions

Array size n (1–100), followed by n integers between -1,000,000 and 1,000,000.

UNDERSTAND THE IDEA

Explanation

Compare neighboring elements and swap them when the left value is greater. After each pass, the largest remaining value has moved to the end.

The already-settled suffix does not need another comparison. A swapped flag stops early when a pass makes no changes.

PLAN BEFORE CODING

Algorithm

  1. Read the array.
  2. Compare adjacent elements in the unsettled portion.
  3. Swap pairs that are out of ascending order.
  4. Stop early if no swap occurs in a pass.
  5. Print the sorted array.

SEE THE CONTROL FLOW

Flowchart

Follow the arrows from Start. Diamonds ask a question; labeled arrows show the answer. A returning arrow repeats a loop. Function internals are grouped where needed; later input checks follow the rules in the program.

Flowchart for Bubble sort in ascending order: input, decisions, processing, output and loop paths

On a phone, scroll sideways to read the diagram at full size. Open full-size flowchart ↗

C17

Complete C program

Download .c
#include <stdio.h>
#define MAX_SIZE 100

int readArray(int a[], int *n) {
    if (scanf("%d", n) != 1 || *n < 1 || *n > MAX_SIZE) return 0;
    for (int i = 0; i < *n; ++i)
        if (scanf("%d", &a[i]) != 1 || a[i] < -1000000 || a[i] > 1000000) return 0;
    return 1;
}

void printArray(const int a[], int n) {
    for (int i = 0; i < n; ++i) printf("%s%d", i == 0 ? "" : " ", a[i]);
    putchar('\n');
}

void bubbleSort(int a[], int n) {
    for (int pass = 0; pass < n - 1; ++pass) {
        int swapped = 0;
        for (int j = 0; j < n - 1 - pass; ++j) {
            if (a[j] > a[j + 1]) {
                int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp;
                swapped = 1;
            }
        }
        if (!swapped) break;
    }
}

int main(void) {
    int a[MAX_SIZE], n;
    if (!readArray(a, &n)) { puts("Invalid input."); return 1; }
    bubbleSort(a, n);
    printf("Ascending: "); printArray(a, n);
    return 0;
}
Open in compiler ↗

Code loads into the existing compiler. Enter the sample input there; sign-in and execution rules stay the same.

Compile and run locally
gcc -std=c17 bubble-sort-ascending.c -o lab
./lab

On Windows, run .\lab.exe after compiling with GCC. The interest program requires the math library where applicable.

FOLLOW THE VALUES

Dry run

Step / stateOperationResult
Start5 1 4 2Unsorted
Pass 11 4 2 55 settles at the end
Pass 21 2 4 54 settles
Pass 3No swapsStop

CHECK THE BEHAVIOR

Sample input & output

Each output below was produced by compiling and running this exact program. Input values are entered in the stated order; the examples do not print input prompts.

Sample 1

INPUT
4
5 1 4 2
OUTPUT
Ascending: 1 2 4 5

Sample 2

INPUT
5
3 -1 3 0 -2
OUTPUT
Ascending: -2 -1 0 3 3

Sample 3

INPUT
1
7
OUTPUT
Ascending: 7

Common mistakes

  • The condition j < n - 1 - pass prevents reading beyond a[j + 1].
  • Reset swapped at the beginning of each pass.

WHY THIS GROWTH RATE?

Time and space complexity

Time O(n²) worst case and O(n) best case with early stopping; O(1) additional space.

In the worst case, passes compare (n − 1), (n − 2), …, 1 adjacent pairs. Their sum is n(n − 1)/2, whose largest term grows as n². Swapping each pair has constant cost, so worst-case time is O(n²).

This implementation records whether a pass made a swap. An already sorted array needs one pass of n − 1 comparisons, then stops: O(n) best-case time. It sorts in the original array and uses one temporary value plus counters, giving O(1) auxiliary space.

Big-O describes how work grows as the stated input quantity grows; fixed factors and lower-order terms are omitted. The analysis treats fixed-width arithmetic as constant cost and the published limits as practical safety bounds.