Home » c++, programming
Bookmark and Share

Bubble Sort in C++

Written by Sandeep (351) on 12 July 2009 and received No Comments
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.
Program:

#include <stdio.h>
#include <iostream.h>

void bubbleSort(int *array,int length)//Bubble sort function
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<i;j++)
{
if(array[i]>array[j])
{
int temp=array[i]; //swap
array[i]=array[j];
array[j]=temp;
}

}

}

}

void printElements(int *array,int length) //print array elements
{
int i=0;
for(i=0;i<10;i++)
cout<<array[i]<<endl;
}

void main()
{

int a[]={9,6,5,23,2,6,2,7,1,8}; // array to sort
bubbleSort(a,10); //call to bubble sort
printElements(a,10); // print elements
}

Get Your Blog Migrated freely to WordPress!

Related posts:

  1. Selection Sort in C++
  2. Heap Sort in C++
  3. Bucket Sort in C++
  4. Merge Sort in C++
  5. Insertion Sort in C++

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

*All comments will be moderated, Read our Comments Policy.

CommentLuv Enabled