Bubble  Sort   Algorithm

Bubble Sort Algorithm

·

2 min read

Table of contents

Bubble Sort

Bubble sort is a simple sorting algorithm that repeatedly steps through a list of items, 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 it works:

Start with an unsorted list of items.

Compare the first two items in the list. If the first item is greater than the second item, swap them.

Move to the next pair of items in the list and compare them in the same way. Continue comparing and swapping until you reach the end of the list.

Now, the largest item in the list should be at the end of the list. Start again from the beginning of the list, comparing and swapping pairs of items until you reach the second-to-last item in the list.

Repeat steps 3 and 4 until the entire list is sorted.

Here's the bubble sort algorithm:

#include<iostream>

using namespace std;

int main(){

int size;

cout<< " Enter an arrat size:";

cin>> size;

int arr[size];

cout<< "Enter array elements:"<<endl;

// loop for array element input :

for (int i =0;i<size;i++){

cin>> arr[i];

}

cout<< "Before Sort array:"<<endl;

for(int i=0;i<size;i++){

cout<< arr[i] << " " ;

}

// Bubble sort start

for (int outloop = 0;outloop <size-1;outloop++){

for(int i = 0 ;i< size - outloop-1;i++){

if(arr[i]>arr[i+1]){

int temp = arr[i];

arr[i] = arr[i+1];

arr[i+1]= temp;

}

}

}

// Print sorted array

cout<< endl<<"Sorted array:"<<endl;

for(int i=0;i<size;i++){

cout<< arr[i] << " " ;

}

return 0;

}