Sort an Array in Ascending Order (Bubble Sort)

Sort an Array in Ascending Order (Bubble Sort)

In this exercise, you will master one of the most fundamental operations in computer science: Array Sorting. You will implement the Bubble Sort algorithm to reorder a dataset from the smallest to the largest value.

Sorting is critical for optimizing other processes, such as binary searching or data visualization. By the end of this challenge, you will understand how nested loops and element swapping work together to organize information efficiently in C++.

Implementation Details

1. Nested Iteration

We use two loops: the outer loop tracks the number of passes, while the inner loop compares adjacent elements.

2. The Swap Logic

If an element is larger than the next one, we swap them using a temporary variable to avoid losing data.

3. Optimization

With each pass, the largest remaining element "bubbles up" to its correct position, reducing the work for the next iteration.

Objective

  • 1. Create a sortArray function using the Bubble Sort logic.
  • 2. Implement nested loops to compare and swap adjacent numbers.
  • 3. Develop a helper function to print the array before and after sorting.
  • 4. Ensure the final output is strictly in ascending order.

Example C++ Exercise

bubble_sort.cpp Algorithms
#include <iostream>
using namespace std;

// Function to sort an array in ascending order using Bubble Sort
void sortArray(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            // Swap if the current element is greater than the next
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    int numbers[] = {34, 12, 5, 9, 27, 43};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    sortArray(numbers, size);

    cout << "Sorted array: ";
    printArray(numbers, size);

    return 0;
}

Example Output:

Sorted array: 5 9 12 27 34 43
Related Topics
Bubble Sort Algorithm Array Reordering Time Complexity Analysis Nested Loops in C++ Swap Logic and Temp Variables

Share this Training

Help your peers master sorting algorithms!

© C++ Programming Exercises. Master the art of performance coding.