Bubble Sort in Ascending Order in C++

1. Introduction

In this blog post, we will learn how to write a C++ program to sort an array of integers in an Ascending Order using the Bubble Sort algorithm.

Bubble Sort is one of the simplest sorting algorithms, often taught to beginners. It works by repeatedly stepping through the list, comparing adjacent items, and swapping them if they're in the wrong order. The process is repeated until no swaps are needed, ensuring the list is sorted.

2. Program Overview

The C++ program below includes:

1. swap(): A utility function to swap two elements.

2. bubbleSort(): The main function that sorts the array using Bubble Sort.

3. printArray(): A function to display the array elements.

4. main(): The main function to drive the program.

3. Code Program

#include<iostream>
using namespace std;

// Utility function to swap two elements
void swap(int &x, int &y) {
    int temp = x;
    x = y;
    y = temp;
}

// Main function to perform bubble sort
void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        for (int j = 0; j < n-i-1; j++) {
            // Swap if the current element is greater than the next
            if (arr[j] > arr[j+1]) {
                swap(arr[j], arr[j+1]);
            }
        }
    }
}

// Function to print an array
void printArray(int arr[], int size) {
    for (int i=0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Driver function
int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << "Original array: \n";
    printArray(arr, n);

    bubbleSort(arr, n);

    cout << "Sorted array in ascending order: \n";
    printArray(arr, n);
    return 0;
}

Output:

Original array:
64 34 25 12 22 11 90
Sorted array in ascending order:
11 12 22 25 34 64 90

4. Step By Step Explanation

1. swap(): This function is a utility to swap two elements. It's used inside our bubble sort function whenever two adjacent elements are in the wrong order.

2. bubbleSort(): Here's where the magic happens. The outer loop runs for every element, while the inner loop runs for decreasing counts. This is because with every outer loop iteration, the largest element bubbles up to its correct position. If the current element (arr[j]) is greater than the next element (arr[j+1]), they are swapped.

3. printArray(): This function prints the array elements, aiding in visual verification before and after sorting.

4. main(): Initializes an example array, prints it, runs the bubble sort, and then prints the sorted array.

The algorithm's simplicity makes it intuitive, but it's not the most efficient for large lists. It has a worst-case and average-case time complexity of O(n^2), where 'n' is the number of items being sorted. Better algorithms, like QuickSort or MergeSort, are recommended for larger datasets.

Related C++ Programs on Sorting Algorithms

Comments