Explain Bubble Sort in C with an Array example

Bubble Sort in C

Bubble Sort in C: Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which means the list is sorted.

Steps of Bubble Sort in C

  • Compare the first two elements of the array.
  • If the first element is greater than the second, swap them.
  • Move to the next pair of elements, compare them, and swap if necessary.
  • Repeat the process for the entire array.
  • The largest element “bubbles up” to the end of the array after the first pass.
  • Repeat the process for the rest of the array until it’s sorted.

Code Example of Bubble Sort in C

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    for (i = 0; i < n-1; i++) {
        // Last i elements are already in place
        for (j = 0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                // Swap arr[j] and arr[j+1]
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

void printArray(int arr[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    printf("Unsorted array: \n");
    printArray(arr, n);
    bubbleSort(arr, n);
    printf("Sorted array: \n");
    printArray(arr, n);
    return 0;
}

Explanation of the Bubble Sort in C Code

  1. bubbleSort Function:
    • This function takes an array and its size as parameters.
    • It uses two nested loops
      • The outer loop runs n-1 times where n is the number of elements in the array.
      • The inner loop runs n-i-1 times for each pass, reducing the number of elements to be checked after each pass since the largest element in the unsorted portion moves to its correct position.
    • Inside the inner loop, adjacent elements are compared, and if the left element is greater than the right element, they are swapped.
  2. printArray Function:
    • This function prints the elements of the array.
  3. main Function:
    • An array of integers is defined and its size is determined.
    • The unsorted array is printed.
    • The bubbleSort function is called to sort the array.
    • The sorted array is printed.

Example

For the array {64, 34, 25, 12, 22, 11, 90}, the bubble sort will perform the following steps:

  • Pass 1: {34, 25, 12, 22, 11, 64, 90}
  • Pass 2: {25, 12, 22, 11, 34, 64, 90}
  • Pass 3: {12, 22, 11, 25, 34, 64, 90}
  • Pass 4: {12, 11, 22, 25, 34, 64, 90}
  • Pass 5: {11, 12, 22, 25, 34, 64, 90}

After these passes, the array is sorted.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *