Tuesday, May 12, 2015

Selection Sort


It is a simplest algorithm.
First look for the minimum in the array and then swap that element with the 0th position. Then find the second minimum element and swap with the index 1 element and so on.


SelectionSort ( A , n ) 
{
      for i <--- 0 to n-2
       {
            min <-- i
            for j <--- i+1 to n-1
             {
                   if ( A[i] <  A[min] )
                           min <--- j
                   
                    temp <-- A[i]
                    A[i] <--- A[min]
                    A[min] <-- temp
              }
        }
}
Read more

Bubble Sort Algorithm



In this algorithm, we scan the array from left to right multiple times. We will call each scan one pass on the array like we will first look at the 0th element then look at the index 1 and so on.

BubbleSort(A,n) // "A" is the array name and "n" is the length of array
{
       for k <---- 1 to n-1
       {
             flag <------ 0
             for i <---- 0 to n-k-1
              {
                     if ( A[i] > A[i+1] )
                      {
                            swap ( A[i] , A[i+1] )
                            flag <----- 1
                       }
               }
               if ( flag == 0 ) break
        }
}
Read more