๐Ÿ“”
Algorithms Analysis & Design
  • Algorithm Analysis & Design
  • ๐ŸšขSearching and Sorting
    • Introduction-Search
    • Linear Search
    • Binary Search
    • Interpolation Search
    • Introduction-Sorting
    • Bubble Sort
    • Selection Sort
    • Counting Sort
  • ๐Ÿ’ธGreedy Method
    • Introduction
    • Activity Selection
    • Fractional Knapsack Problem
    • Graph Colouring
  • ๐Ÿš Backtracking
    • Introduction
    • Hamiltonian Path/Cycle Problem
    • N Queen Problem
    • Rat in a Maze
    • Knight's Tour Problem
  • โš”๏ธDivide and Conquer
    • Introduction
    • Strassen's Matrix multiplication
    • Karatsuba algorithm
    • Tower of Hanoi
    • Closest Pair
  • ๐Ÿ’ฃDynamic Programming
    • Introduction
    • Longest Common Subsequence
    • Floyd-Warshall Algorithm
    • 0-1 Knapsack problem
    • Dice Throw
  • ๐Ÿ“ˆGraph
    • Introduction
    • DFS
    • Dictionary Game
    • BFS
    • Flood Fill Algorithm
    • Minesweeper Lite
  • ๐Ÿ”ขNumber Theory
    • Introduction
    • GCD
    • Factorial
    • IsPrime | School Method
    • IsPrime | Fermat's Little Theorem
    • IsPrime | Miller-Rabin Method
  • ๐ŸŒฎReferences
Powered by GitBook
On this page

Was this helpful?

  1. Searching and Sorting

Bubble Sort

The simplest sorting algorithm is bubble sort. It works by comparing each adjacent pair of elements and swapping them if they are out of order. It works by walking through the list to be sorted many times, comparing two items at a time and exchanging them if they are out of order. The process is continued until no swaps are required, indicating that the list is sorted.

Time complexity of this algorithm are of ฮŸ(n^2) where n is the number of items.

Algorithm

for i=N-1 to 2 {

set swap flag to false

for j=1 to i {

if list[j-1] > list[j]

swap list[j-1] and list[j]

set swap flag to true

}

if swap flag is false, break. The list is sorted.

}

[NOTE: In each pass, the largest item โ€œbubblesโ€ down the list until it settles in its final position. This is where bubble sort gets its name.]

Example,

Suppose we have a list of array of 5 elements A[5]={40,50,30,20,10}. We have to sort this array using bubble sort algorithm.

We observe in algorithm that Bubble Sort compares each pair of array element unless the whole array is completely sorted in an ascending order. After every iteration the highest values settles down at the end of the array. Hence, the next iteration need not include already sorted elements.

PreviousIntroduction-SortingNextSelection Sort

Last updated 3 years ago

Was this helpful?

Bubble-sort-example-MSA Technosoft
๐Ÿšข