Friday 5 February 2016

Simplest way to learn Bubble Sort

On this link I told you the simplest way to learn selection sort. But selection sort is not the best preferred sorting method.
Selection sort is little slower than the bubble sort.
Suppose we have an array : 2, 7, 4, 1, 5, 3
Key Point to Note:
  • Here we are going to scan each element of the array from left to right multiple times.
  • The reason for scanning the array multiple times is that when we are at some perticular element then we will compare that element with its next adjecent element. (i.e if we are at 0 index, then we will compare that element with the element at index 1.)
  • And if the element at the current position is greater than the element at next position then we will swap these two elements. (if in case we are at index 1, then swapping will take place between ARRAY[1] and ARRAY[2]).
  • Similarly after one complete scan of the array we will get a new array which will be: 2,4,1,5,3,7
  • Clearly, we can note that the element which is largest in the array is not present at the last index of the array.

Why we call this at bubble sort?
We can clearly notice that the largest element has kind of bubbled up to the last index in the array. So this sorting method is known at the bubble sort.

Sudo code for one pass:

for ( i = 0 to size-2 )
    if Array[i] > Array[i+1]
        swap( Array[i] , Array[i+1] )


  • Now after the second pass the array will be : 2, 1, 4, 3, 5, 7  
  • Similarly we need to have such "size-1" passes.

Reason for "size-1" passes:
we need only size-1 passes because if we have sorted the size-1 elements then the last element left will already be sorted.
  • So now we need to have another loop to control the number of passes required. So we need to write two loops.
  • One Loop will count the number of passes(outer loop) and the other loop will be used to swap the elements of array if required(inner loop)

So now we can write the code of bubble sort.

Bubble Sort in Ascending order:
#include<iostream>
void swap(int Array[], int index)
{
    int temp = Array[index];
    Array[index] = Array[index+1];
    Array[index+1] = temp;
}
void bubbleSort(int Array[], int size)
{
    int flag = 0;
    for(int i = 0; i < size-1 && flag == 0; i++)
    {
        for(int j = 0; j < size-i-1; j++ )
        {
            if(Array[j] > Array[j+1])
            {
                 swap(Array, j);
                 flag = 1;
            }
        }
        if(flag == 0)   //no swapping haapen so break the loop
            break;
        flag = 0;
    }
}
int main()
{
    int size, Array[50];
    std::cout<<"\n Enter the number of elements in the array : ";
    std::cin>>size;
    std::cout<<"\n Enter the elements of the array : \n";
    for(int i = 0; i < size; i++)
        std::cin>>Array[i];
    bubbleSort(Array, size);
    std::cout<<"\n The array after soring is : \n";
    for(int i = 0; i < size; i++)
        std::cout<<" "<<Array[i];
    return 0;
}

1 comment: