110 likes | 233 Views
CISC 101: Fall 2011. Hossain Shahriar shahriar@cs.queensu.ca. Announcement and reminder!. Final exam date December 19: 4pm-6pm Topics to be covered in this lecture Sort. Sort. Order elements in a collection of object (e.g., number, string) Ascending Descending
E N D
CISC 101: Fall 2011 HossainShahriar shahriar@cs.queensu.ca
Announcement and reminder! • Final exam date • December 19: 4pm-6pm • Topics to be covered in this lecture • Sort
Sort • Order elements in a collection of object (e.g., number, string) • Ascending • Descending • We will discuss on two types of sort • Bubble • Insertion
Bubble sort (example) Src: http://lionel.textmalaysia.com/files/2010/09/bubblesort.png
Bubble sort • Observations • We are swapping two neighboring numbers repeatedly • Continue swapping until we reach the end of the list
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 jth and j+1th • 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(n2) • When input numbers are sorted in descending order and we are sorting in ascending order
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
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 • …
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 betwniand min
Selection sort • Time complexity • O(n2)
Extra quiz and misc • Search and sorting • Wednesday (Nov 30, Quiz 4) • Next Monday (Nov 28, Quiz 3) • Final exam starts on Dec 19th at 4pm • Assignment 3 due by December 19th (firm and no extension) • Take home assignments will not be accepted after December 19th