Bubble Sort in Ascending Order in C

1. Introduction

Bubble Sort is a simple and intuitive sorting algorithm that works by repeatedly stepping through the list, comparing adjacent items, and swapping them if they are in the wrong order. The process is repeated until no more swaps are needed, which indicates that the list is sorted.

2. Program Overview

In this post, we will cover the implementation of the Bubble Sort algorithm in C to sort an array of integers in ascending order. 

The program will have the following structure:

1. swap: A utility function to swap two integers.

2. bubbleSort: The main function that implements Bubble Sort.

3. printArray: A function to print the contents of the array.

3. Code Program

#include <stdio.h>

void swap(int *xp, int *yp) {
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void bubbleSort(int arr[], int n) {
    int i, j;
    for (i = 0; i < n-1; i++)
        for (j = 0; j < n-i-1; j++)
            if (arr[j] > arr[j+1])
                swap(&arr[j], &arr[j+1]);
}

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]);
    bubbleSort(arr, n);
    printf("Sorted array: \n");
    printArray(arr, n);
    return 0;
}

Output:

Sorted array:
11 12 22 25 34 64 90

4. Step By Step Explanation

The bubbleSort function operates by repeatedly comparing and swapping adjacent elements if they are in the wrong order. 

After the first pass, the largest element is "bubbled up" to its correct position at the end of the array. 

With each subsequent pass, the next largest element is bubbled up to its correct position, reducing the effective size of the unsorted portion of the array by one. 

This continues until the array is fully sorted.

Related C Programs on Sorting Algorithms

  1. Bubble Sort in Ascending Order in C
  2. Bubble Sort in Descending Order in C
  3. Selection Sort in Ascending Order in C
  4. Selection Sort in Descending Order in C
  5. Insertion Sort in Ascending Order in C
  6. Insertion Sort in Descending Order in C
  7. Merge Sort in Ascending Order in C
  8. Merge Sort in Descending Order in C
  9. Quick Sort in Ascending Order in C
  10. Quick Sort in Descending Order in C
  11. Heap Sort in Ascending Order in C
  12. Heap Sort in Descending Order in C


Comments