Bubble Sort
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
Here's how Bubble Sort works in C++:
- Start with an unsorted array of n elements.
- Create a loop that will repeat n-1 times, as each pass will place the largest unsorted element into its proper position.
- Within each pass, create a nested loop that will compare adjacent elements and swap them if they are in the wrong order.
- After each pass, the largest unsorted element is moved to its proper position.
- Continue the outer loop until no more passes are needed.
Here's the code implementation:
#include <iostream>using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) { // Loop through array elements
for (int j = 0; j < n-i-1; j++) { // Loop through unsorted elements
if (arr[j] > arr[j+1]) { // Swap if the element found is greater than the next element
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout<<"Sorted array: \n";
for (int i = 0; i < n; i++)
cout<<arr[i]<<" ";
return 0;
}
In this implementation, we first create a function called bubbleSort
that takes an integer array and its size as parameters. We then use two nested loops to loop through each element of the array and compare it to its adjacent element. If the current element is greater than the next element, we swap them. We continue doing this until the entire array is sorted.
In the main
function, we create an unsorted integer array and pass it to the bubbleSort
function along with its size. After the array is sorted, we use a loop to print out each element in the sorted array.
Overall, Bubble Sort is a simple and intuitive sorting algorithm that is easy to implement in C++. However, its time complexity is O(n^2), making it inefficient for large data sets.
Comments
Post a Comment