Professional Documents
Culture Documents
10-Sorting Algorithms A) Bubble Sort
10-Sorting Algorithms A) Bubble Sort
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]
Step 3 – if one element is greater than the second element that is just next to it then,
Implementation in C++
#include <iostream>
{
3
Data Structure & Algorithms
length = 5;
for(i=0; i<length; i++)
cin>>A[i];
}
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}
}
{
cout<<A[i]<<"\t";
system("PAUSE");
return 0;
}