Site icon i2tutorials

Data Structures-Bubble sort

Bubble sort

 

Bubble sort is a comparison-based sorting algorithm, in which the adjacent elements are compared and the elements are swapped if they are not in order.

 

How does bubble sort work?

Let’s assume an unsorted array: 14, 33, 27, 35, 10.

  1. Bubble sort checks the first two elements to see which is greater. So, the list will be 14, 33, 27, 35, 10.
  2. Next, it compares the second and the third element: 14, 27, 33, 35, 10.
  3. Then 33 and 35 are compared: 14, 27, 33, 35, 10.
  4. Then we move to the next element, as 35 is greater than 10, therefore the list is 14, 27, 33, 10, 35.
  5. After the second iteration, the array becomes 14, 27, 10, 33, 35.
  6. After another iteration: 14, 10, 27, 33, 35.
  7. Finally, after the array is sorted: 10, 14, 27, 33, 35.

 

Algorithm:

 

Pseudocode:

procedure bubbleSort( list : array of items )

   loop = list.count;
   
   for i = 0 to loop-1 do:
      swapped = false
  
      for j = 0 to loop-1 do:
      
         /* compare the adjacent elements */   
         if list[j] > list[j+1] then
            /* swap them */
            swap( list[j], list[j+1] )   
            swapped = true
         end if
         
      end for
      
      /*if no number was swapped that means 
      array is sorted now, break the loop.*/
      
      if(not swapped) then
         break
      end if
      
   end for
   
end procedure return list

Reference

Bubble Sort

Exit mobile version