top of page
Writer's picturecompnomics

Bubble Sort in C Programming



 

#include <stdio.h>

void swap(int *a, int *b) {
  int temp = *a;
  *a = *b;
  *b = temp;
}

void bubble_sort(int arr[], int n) {
  // Loop through n-1 iterations
  for (int i = 0; i < n - 1; i++) {
    // Flag to track if any swaps occurred
    int swapped = 0;

    // Compare adjacent elements and swap if needed
    for (int j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        swap(&arr[j], &arr[j + 1]);
        swapped = 1; // Set flag if a swap occurred
      }
    }

    // If no swaps happened in the inner loop, the array is already sorted
    if (!swapped) {
      break; // Early termination
    }
  }
}

int main() {
  int arr[] = {64, 34, 25, 12, 22, 11, 90};
  int n = sizeof(arr) / sizeof(arr[0]);

  printf("Unsorted array: ");
  for (int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");

  bubble_sort(arr, n);

  printf("Sorted array: ");
  for (int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");

  return 0;
}

Explanation:

  1. The swap function exchanges the values of two integers pointed to by a and b.

  2. The bubble_sort function takes an array and its size as arguments.

  3. It iterates through the array n-1 times, representing the number of passes needed to sort n elements.

  4. Inside each pass, there's an inner loop that compares adjacent elements.

  5. If the elements are in the wrong order, they are swapped using the swap function.

  6. A flag swapped is used to track if any swaps occurred in the inner loop.

  7. If no swaps happen, it means the array is already sorted, and the loop can be terminated early.

  8. The main function demonstrates how to use the bubble_sort function with an example array.

This code implements the basic bubble sort algorithm, which has a time complexity of O(n^2) in the worst case. Although there are more efficient sorting algorithms, bubble sort remains a simple and intuitive example to understand sorting concepts.

52 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page