Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hossain Shahriar Announcement and reminder! Final exam date December 19: 4pm-6pm Topics to be covered in this lecture Sort.

Similar presentations


Presentation on theme: "Hossain Shahriar Announcement and reminder! Final exam date December 19: 4pm-6pm Topics to be covered in this lecture Sort."— Presentation transcript:

1 Hossain Shahriar shahriar@cs.queensu.ca

2 Announcement and reminder! Final exam date December 19: 4pm-6pm Topics to be covered in this lecture Sort

3 Order elements in a collection of object (e.g., number, string) Ascending Descending We will discuss on two types of sort Bubble Insertion

4 Bubble sort (example) Src: http://lionel.textmalaysia.com/files/2010/09/bubblesort.png

5 Bubble sort Observations We are swapping two neighboring numbers repeatedly Continue swapping until we reach the end of the list

6 Bubble sort (algorithm) def bubble(list): for i in range(0, len(list) - 1): for j in range(0, len(list) - i - 1): if list[j] > list[j + 1]: #compare two neighboring num list[j], list[j + 1] = list[j + 1], list[j] # swap j th and j+1 th If we want the list to be in descending order, replace the comparison statement if list[j] < list[j + 1] Time Worst case time: n*(n-1) = O(n 2 ) When input numbers are sorted in descending order and we are sorting in ascending order

7 Bubble sort (algorithm) How to measure the time in python? import time import math t1 = time.clock() #record the clock in ms math.sqrt(340) #performing the function t2 = time.clock() #record the clock in ms print ‘sqrt(340) took’, (t2-t1)*1000, ‘ sec’ Take home assignment (last one) Write a bubble sort algorithm that sorts a list of input strings in descending order Measure how much time your algorithm takes

8 Selection sort Find the smallest in the list (1 to n) Swap it with the element in the first position Find the second smallest element (2 to n) Swap it with the element in the second position Find the second smallest element (3 to n) Swap it with the element in the third position …

9 Selection sort (algorithm) def selection(list): for i in range(0, len (list)): min = i #we assume that the first number is min for j in range(i + 1, len(list)): #this loop finds the min if list[j] < list[min]: min = j list[i], list[min] = list[min], list[i] # swap betwn i and min

10 Selection sort Time complexity O(n 2 )

11 Extra quiz and misc Search and sorting Wednesday (Nov 30, Quiz 4) Next Monday ( Nov 28, Quiz 3) Final exam starts on Dec 19 th at 4pm Assignment 3 due by December 19 th (firm and no extension) Take home assignments will not be accepted after December 19 th


Download ppt "Hossain Shahriar Announcement and reminder! Final exam date December 19: 4pm-6pm Topics to be covered in this lecture Sort."

Similar presentations


Ads by Google