Docsity

Analysis of Bubblesort and Mergesort Algorithms: Complexity and Runtime, Essays (high school) of Computer science

Partial preview of the text

Download Analysis of Bubblesort and Mergesort Algorithms: Complexity and Runtime and more Essays (high school) Computer science in PDF only on Docsity!

Big O of Different

sorting Algorithm

Week 7

Sorting Algorithms

  • Bubblesort
    • Brute-force method of sorting
    • Loop inside of a loop
  • Mergesort
    • Divide and conquer approach
    • Recursively call, splitting in half
    • Merge sorted halves together

Bubblesort Review

Bubblesort works by comparing and swapping values in a list

Bubblesort Review

Bubblesort works by comparing and swapping values in a list

Largest value correctly placed

Bubblesort Complexity

Look at the relationship between the two loops:

  • Inner is nested inside outer
  • Inner will be executed for each iteration of outer

Therefore the complexity is:

O((N-1)*(N/2)) = O(N 2 /2 – N/2) = O(N 2 )

LB

O(N 2 ) Runtime Example

Assume you are sorting 250,000,000 items N = 250,000, N 2 = 6.25 x 10^16 If you can do one operation per nanosecond (10-9^ sec) which is fast! It will take 6.25 x 10 7 seconds So 6.25 x 10 7 60 x 60 x 24 x 365 = 1.98 years

Mergesort

Log N

Log N

Analysis of Mergesort

Phase I

  • Divide the list of N numbers into two lists of N/ numbers
  • Divide those lists in half until each list is size 1 Log N steps for this stage.

Phase II

  • Build sorted lists from the decomposed lists
  • Merge pairs of lists, doubling the size of the sorted lists each time Log N steps for this stage.

O(NLogN) Runtime Example

Assume same 250,000,000 items N*Log(N) = 250,000,000 x 8. = 2, 099, 485, 002

With the same processor as before

2 seconds

Questions?