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.
Logic Tip:
Bubble Sort has a time complexity of $O(n^2)$. While simple to implement and great for learning, for very large datasets, professional developers often use std::sort from the <algorithm> library.
Objective
- 1. Create a
sortArrayfunction 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
#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;
}