Data Structures and Algorithms - Old Questions
7. Explain Bubble sort algorithm. Illustrate it with an example.
Bubble sort algorithm arranges values by iterating over the list several times and in each iteration the larger value gets bubble up to the end of the list. This algorithm uses multiple passes and in each pass the first and second data items are compared. if the first data item is bigger than the second, then the two items are swapped. Next the items in second and third position are compared and if the first one is larger than the second, then they are swapped, otherwise no change in their order. This process continues for each successive pair of data items until all items are sorted.
Algorithm for Bubble Sort
Let a[n] be an array list of size n.
void bubbleSort(int a[], int n)
{
int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if( a[j] > a[j+1])
{
// swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
Example:
Consider the array list:
5 | 1 | 4 | 2 | 8 |
Source: w3resource.com