Algorithm for Bubble Sort


Step 1: Repeat Step 2 For 1=0 to N-1 
Step 2: Repeat For J= 0 to N-I 
Step 3: IF A[J] > A[J+1] 
            SWAP A[J] and A[J+1] 
          [END OF INNER LOOP] 
        [END OF OUTER LOOP] 
Step 4: EXIT

Program

Let's consider an array with values {5, 1, 6, 2, 4, 3} 
int a[6] = {5, 1, 6, 2, 4, 3};
int i, j, temp;
for(i = 0; i < 6; i++)
{
 for(j = 0; j < 6-i-1; j++)
 {
  if(a[j] > a[j+1])
  {
   temp = a[j];
   a[j] = a[j+1];
   a[j+1] = temp; 
  }
 }
} 

Explanation

Above is the algorithm, to sort an array using Bubble Sort. Although the above logic will sort and unsorted array, still the above algorithm isn't efficient and can be enhanced further. Because as per the above logic, the for loop will keep going for six iterations even if the array gets sorted after the second iteration.