The Bubble Sort is one of the popular and easy Sorting algorithms used to arrange the array of elements in ascending or descending order. In Bubble Sort Algorithm, we continuously keep on swapping two adjacent elements if they are present in the incorrect order. The worst-case time complexity of this algorithm is very high so it is not considered a suitable algorithm when there is a huge amount of data.
Working of Bubble Sort Algorithm.
Steps for Bubble Sort Algorithm (Ascending Order):
- Run two nested loops and traverse the given array where the outer loop will run n-1 times and the inner loop will run n-i-1 times.
- In each iteration, we will pick two adjacent elements of the array and if arr[j] > arr[j+1] then we will swap their position else we will move to the next adjacent element. After completing each iteration the greatest element will move to the right end of the array.
- In the end, you will see that no swapping is required and all elements are arranged in sorted order.
Below is the C++ Code Implementation of the Bubble Sort Algorithm.
#include<iostream> using namespace std; //Implementation of 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++){ //Comparing two adjacent element if(arr[j] > arr[j+1]){ swap(arr[j], arr[j+1]); } } } } int main(){ int arr[] = {10, 23, 5, 8, 21, 15}; //size of given array int n = sizeof(arr)/sizeof(arr[0]); bubbleSort(arr, n); cout<<"Sorted Array:"; for(int i = 0; i < n; i++){ cout<<arr[i]<<" "; } }
Output:
Sorted Array:5 8 10 15 21 23
- Time Complexity: O(n^2)
- Space Complexity: O(1)
See more:
Great Work!
ReplyDelete