Group
Search and Sort Algorithms in C++
Objective
1. Create a function named bubbleSort that takes an array and its size as parameters.
2. Implement the Bubble Sort logic using nested loops to repeatedly compare and swap adjacent elements if needed.
3. In the main function, define an array of integers and display it before and after sorting.
4. Use standard output to show the array's state before and after applying the sorting algorithm.
Implement the Bubble Sort algorithm.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for input and output operations
using namespace std;
// Function to perform Bubble Sort on an array
void bubbleSort(int arr[], int n) {
// Outer loop controls the number of passes
for (int i = 0; i < n - 1; i++) {
// Inner loop compares adjacent elements and swaps them if necessary
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to print the elements of the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
// Define an array of integers to be sorted
int data[] = {64, 34, 25, 12, 22, 11, 90};
int size = sizeof(data) / sizeof(data[0]); // Calculate the number of elements
// Display the original array
cout << "Original array: ";
printArray(data, size);
// Call the bubbleSort function to sort the array
bubbleSort(data, size);
// Display the sorted array
cout << "Sorted array: ";
printArray(data, size);
return 0; // End of program
}
Output
Original array: 64 34 25 12 22 11 90
Sorted array: 11 12 22 25 34 64 90