Computer >> Computer tutorials >  >> Programming >> Programming

Difference Between Bubble Sort and Selection Sort


In this post, we will understand the difference between Bubble Sort and Selection Sort

Bubble Sort

  • It is a simple sorting algorithm.

  • It iterates through the list, and compares adjacent pairs of elements to sort them.

  • Based on the adjacent elements, swaps are made.

  • It is efficient in comparison to selection sort.

  • It is slower in comparison to selection sort.

  • It uses item exchanging to swap elements.

  • The elements are repeatedly swapped until all the elements are in the right order.

Following is the Bubble Sort Algorithm

Algorithm

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

Selection Sort

  • First, the minimum or the maximum number from the list is obtained.

  • The list is sorted in ascending or descending order.

  • It selects the minimum or maximum element from unsorted sub-array and puts it in the next position of the sorted sub-array.

  • It is considered as an unstable sorting algorithm.

  • The time complexity in all cases is O(n squared).

  • It is less efficient in comparison to insertion sort.

  • The number of comparisons made during iterations is more than the element swapping that is done.

  • The location of every element in the list is previously known.

  • This means the user only searches for the element that needs to be inserted at the specific position.

  • It is efficient compared to the bubble sort

  • It is quick in comparison to bubble sort.

  • It uses item selection.

Following is the Selection Sort Algorithm

Algorithm

Step 1 - Set MIN to location 0
Step 2 - Search the minimum element in the list
Step 3 - Swap with value at location MIN
Step 4 - Increment MIN to point to next element
Step 5 - Repeat until list is sorted