Arrange the array elements in ACS order using Bubble Sort.
Objective
Write a C++ program to sort an array using Bubble Sort.
Algorithm / Approach
- Initialize an unsorted array.
- Run an outer loop
ifrom 1 to the size of the array (number of passes). - Run an inner loop
jfrom 0 up tosize - i. - If the current element is larger than the next element (
ar[j] > ar[j+1]), swap them. - Print the fully sorted array.
main.cpp
#include<iostream>
using namespace std;
int main(){
int i,j,temp;
int ar[8] = {6,5,3,1,8,7,2,4};
cout<<"BEFORE SORTING :\n";
for(i=0; i < 8; i++) {
cout<< ar[i]<< " ";
}
for(i=1; i<=8; i++) {
for(j=0; j < 8-i; j++) {
if(ar[j]>ar[j+1]) {
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
}
}
cout<<"\n\nAFTER SORTING :\n";
for(i=0; i < 8; i++) {
cout<< ar[i]<<" ";
}
return 0;
}
Expected Output
BEFORE SORT : 6 5 3 1 8 7 2 4 AFTER SORT : 1 2 3 4 5 6 7 8
Explanation of the Program
- Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
- It gets its name because larger elements mathematically "bubble" up to the top (the end) of the array during each pass. This is why the inner loop shrinks by
ieach time; we don't need to re-check the elements that have already bubbled to their final correct positions at the end!
Complexity
Time Complexity
O(n^2) - Due to nested loops.
Space Complexity
O(1)