Bubble Sort

Bubble sort is a straightforward sorting method. This sorting algorithm is a comparison-based method that compares each pair of adjacent elements and swaps them if they are not in order. Because its average and worst-case complexity are Ο(n2), where n is the number of items, this approach is not suitable for huge data sets.

Algorithm

We assume list is an array of n elements. We further assume that swap function swaps the values of the given array elements.

begin BubbleSort(list)

   for all elements of list
      if list[i] > list[i+1]
         swap(list[i], list[i+1])
      end if
   end for
   
   return list
   
end BubbleSort

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
0

1 thought on “Bubble Sort”

  1. As I am looking at your writing, slotsite I regret being unable to do outdoor activities due to Corona 19, and I miss my old daily life. If you also miss the daily life of those days, would you please visit my site once? My site is a site where I post about photos and daily life when I was free.

    0

Leave a Comment

Your email address will not be published. Required fields are marked *

6 + 10 =