SORTING ALGORITHMS

bubble sort algorithm

steps

  • compare the first two items in the queue 
  • put the smaller value in extra bin
  • move the largest value among the two to the right and replace the value in the bin to the left

why algorithms

  • gives us an idea of running time
  • helps us decide on the hardware requirements
  • helps us decide on what is feasible vs what's not

compare the two

time complexity

time complexity explained

  • algorithm working on smaller no of elements = less time taken 
  • e.g 1 millisecond to work on 5data items 2 (thereabout) milliseconds on 11 data items
  • what is the order of growth of an algorithm

how to measure time

  • 100 - 10ms
ITEMS ALGORITHM1(ms) ALGORITHM2(ms)
200 20 40
1000 100 1000
10000 1000 100000

prev slide explained

items algorithm1(ms) algorithm2(ms)
200 20 40
1000 100 1000
10000 1000 100000
linear growth quadratic growth

types of time complexity

  • Best case
  • Average case
  • Worst case

ram model of computation

Assumptions made are:

  • we have infinite memory
  • each operation takes one unit of time
  • for each mem access unit time is consumed

Time complexity of bubble sort algorithm (wc)

12 8 7 5 2
8 7 5 2 12
comparison  swap
1 3
1 3
1 3
1 3

total ops: 16

first pass

7 5 2 8 12
comparison  swap
1 3
1 3
1 3

total ops: 12

second pass

5 2 7 8 12
comparison  swap
1 3
1 3

total ops: 8

third pass

2 5 7 8 12
comparison  swap
1 3

total ops: 4

third pass

16+12+8+4

= 4(4+3+2+1)

= 4 (n-1+ n-2 + ... 3 + 2 + 1)

= 2 * n * (n - 1)

= pn^2 + qn + r 

Made with Slides.com