You are on page 1of 3

1

Data Structure & Algorithms

Bubble Sort
In bubble sort, each element is compared with its adjacent element. If the first element is larger
than the second one, then the positions of the elements are interchanged, otherwise it is not
changed. Then next element is compared with its adjacent element and the same process is
repeated for all the elements in the array until we get a sorted array. It means we find the
greatest element and place it at the last of the list or array. Bubble sort is also called exchange
sort.

For example:

First pass

Second pass
2
Data Structure & Algorithms

Third pass

Forth pass

Algorithm
1 Loop i=1 to n
2 Loop j=1 to n-1

3 If A[j]>A[j+1]

4 A[j]<->A[j+1]

In Simple English we can write Selection Sort as Follows:


Step 1 – Loop through 0 to length

Step 2 – Loop through 0 to length

Step 3 – if one element is greater than the second element that is just next to it then,

Step 4 – swap their values with each other


Step 5 − Repeat until list is sorted

Implementation in C++
#include <iostream>

using namespace std;


int main()

{
3
Data Structure & Algorithms

int A[5], length, temp, i, j;

length = 5;
for(i=0; i<length; i++)

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

cin>>A[i];
}

for(i = 0; i < length ; i++)

for(j = 0; j < length-i-1; j++)


{

if( A[j] > A[j+1])

temp = A[j];
A[j] = A[j+1];

A[j+1] = temp;

}
}

cout<<"sorted valued are: \n";

for(i=0; i<length; i++)

{
cout<<A[i]<<"\t";

system("PAUSE");

return 0;
}

You might also like