Skip to main content

ProwessApps

Learn · Practice · Excel

Arrange the array elements in ACS order using Bubble Sort.

C++ Code Example — Data Structure Programs

ADVERTISEMENT

Arrange the array elements in ACS order using Bubble Sort.

Objective

Write a C++ program to sort an array using Bubble Sort.

Algorithm / Approach

  1. Initialize an unsorted array.
  2. Run an outer loop i from 1 to the size of the array (number of passes).
  3. Run an inner loop j from 0 up to size - i.
  4. If the current element is larger than the next element (ar[j] > ar[j+1]), swap them.
  5. 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 i each 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)
ADVERTISEMENT