Algorithm-Bubble sort


Bubble sort algorithm


In the bubble sort, the data set is also divided into two sub-lists: sorted list and unsorted list. The smallest value of the unsorted list is bubbled from the unsorted list and moved to the sorted list. Then the number of sorted list increases by one and the number of unsorted list deceases by one. In bubble sort the adjacent elements are compared and exchanged. Each time one element is moved from the unsorted list to the sorted list, we call sort pass. The number of passes is equal to the number of the data points in the data set minus one. If we have n data points the number of passes to complete the sort process is n-1.

Example C++code for bubble sort:


#include <cstdlib>
#include <iostream>
#include <conio.h>


using namespace std;
void bubblesort(int dataset[], int n){
int i,j;
for(i=0;i<n;i++)
for(j=n-1;j>i;j--)
if(dataset[j]<dataset[j-1])
{
int temp=dataset[j];
dataset[j]=dataset[j-1];
dataset[j-1]=temp;
}

}

int main(){
int arr[5]={23,2,3,34,6}; //unsorted data set
bubblesort(arr,5); //sorting process using bubble sort
for(int i=0;i<5;i++)
cout<<arr[i]<<"\t"; //after sorting


getch();
return 0;

}



Comments

CAPTCHA image



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.