Sorting and Searching

Similar documents
Lecture 25. Sequence Algorithms (Continued)

Lecture 26: Sorting CS 1110 Introduction to Computing Using Python

CS211 Spring 2004 Lecture 06 Loops and their invariants. Software engineering reason for using loop invariants

CS 1110, LAB 13: SEQUENCE ALGORITHMS

CS 1110: Introduction to Computing Using Python Loop Invariants

SORTING 9/26/18. Prelim 1. Prelim 1. Why Sorting? InsertionSort. Some Sorting Algorithms. Tonight!!!! Two Sessions:

Announcements SORTING. Prelim 1. Announcements. A3 Comments 9/26/17. This semester s event is on Saturday, November 4 Apply to be a teacher!

isinstance and While Loops

CS 234. Module 6. October 16, CS 234 Module 6 ADT Dictionary 1 / 33

Lecture 24: Loop Invariants

CS 1110, LAB 12: SEQUENCE ALGORITHMS First Name: Last Name: NetID:

CS 1110 Final, December 8th, Question Points Score Total: 100

Lecture 20. Subclasses & Inheritance

CS 1110: WORKED EXAMPLES REGARDING LOOPS AND INVARIANTS

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Final, December 17th, Question Points Score Total: 100

Lecture 18. Classes and Types

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014

CS1110. Lecture 22: Prelim 2 Review Session. Announcements. Processed prelim regrade requests: on the front table.

CS Lecture 19: Loop invariants

SORTING. Insertion sort Selection sort Quicksort Mergesort And their asymptotic time complexity

PREPARING FOR THE FINAL EXAM

CS 1110 Final, December 16th, 2013

CS 1110 Prelim 2 April 22, 2014

Lecture 19: Subclasses & Inheritance (Chapter 18)

Data Structures and Programming Spring 2014, Midterm Exam.

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

Fault Localization Using Tarantula

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

each node in the tree, the difference in height of its two subtrees is at the most p. AVL tree is a BST that is height-balanced-1-tree.

SEARCHING AND SORTING HINT AT ASYMPTOTIC COMPLEXITY

CSc 110, Spring 2017 Lecture 39: searching

Iteration and For Loops

PREPARING FOR PRELIM 1

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

ASYMPTOTIC COMPLEXITY

AVL Trees Outline and Required Reading: AVL Trees ( 11.2) CSE 2011, Winter 2017 Instructor: N. Vlajic

Conditionals & Control Flow

CS 1110 Final Exam Solutions May 15th, 2014

Binary Search Tree - Best Time. AVL Trees. Binary Search Tree - Worst Time. Balanced and unbalanced BST

CS Prelim 2 Review Fall 2018

CORRECTNESS ISSUES AND LOOP INVARIANTS

CSC 273 Data Structures

CS 234. Module 6. October 25, CS 234 Module 6 ADT Dictionary 1 / 22

Prelim 2 Solution. CS 2110, November 19, 2015, 7:30 PM Total. Sorting Invariants Max Score Grader

Announcements. Lilian s office hours rescheduled: Fri 2-4pm HW2 out tomorrow, due Thursday, 7/7. CSE373: Data Structures & Algorithms

Lecture 17: Classes (Chapter 15)

ASYMPTOTIC COMPLEXITY

Sorting is a problem for which we can prove a non-trivial lower bound.

Sorting. Bubble sort method. Bubble sort properties. Quick sort method. Notes. Eugeniy E. Mikhailov. Lecture 27. Notes. Notes

Lecture 21. Programming with Subclasses

Lecture 8: Conditionals & Control Flow (Sections ) CS 1110 Introduction to Computing Using Python

Today. CISC101 Reminders & Notes. Searching in Python - Cont. Searching in Python. From last time

CS Prelim 2 Review Fall 2012

THE AUSTRALIAN NATIONAL UNIVERSITY Mid Semester Examination September COMP1730 / COMP6730 Programming for Scientists

Sorting and Searching

1 Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Lecture 21. Programming with Subclasses

Synchronization: Semaphores

CS1110. Lecture 1: Final review session. Review materials See website for a version of last year s final with conventions redone to match this year.

Lecture 21. Programming with Subclasses

Binary Search APRIL 25 TH, 2014

C/C++ Programming Lecture 18 Name:

Review 4. Lists and Sequences

UNIT 5C Merge Sort. Course Announcements

CS Prelim 2 Review Fall 2017

CS 1110 Final, December 9th, Question Points Score Total: 100

When a BST becomes badly unbalanced, the search behavior can degenerate to that of a sorted linked list, O(N).

Chapter 5. Quicksort. Copyright Oliver Serang, 2018 University of Montana Department of Computer Science

Prelim 2 Solution. CS 2110, November 19, 2015, 5:30 PM Total. Sorting Invariants Max Score Grader

What is sorting? Lecture 36: How can computation sort data in order for you? Why is sorting important? What is sorting? 11/30/10

Lecture 22. While Loops

Overview of List Syntax

CSCE Java. Lab 13 - Searching & Sorting. Dr. Chris Bourke

CS 1110: Introduction to Computing Using Python Lists and Sequences

Homework 3 Solutions

Data Structures and Algorithms 2018

Lecture 10: Lists and Sequences

Numerical Derivatives

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

Lecture 17: Classes (Chapter 15)

Lecture 18: Using Classes Effectively (Chapter 16)

Prelim 2. CS 2110, November 19, 2015, 7:30 PM Total. Sorting Invariants Max Score Grader

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

University of Waterloo CS240, Winter 2010 Assignment 2

SEARCHING, SORTING, AND ASYMPTOTIC COMPLEXITY. Lecture 11 CS2110 Spring 2016

How invariants help writing loops Author: Sander Kooijmans Document version: 1.0

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

UNIT-2. Problem of size n. Sub-problem 1 size n/2. Sub-problem 2 size n/2. Solution to the original problem

APT Session 2: Python

Lecture 7. Binary Search Trees / AVL Trees

CS 1110 Prelim 2 November 14th, 2013

Advanced Tree. Structures. AVL Tree. Outline. AVL Tree Recall, Binary Search Tree (BST) is a special case of. Splay Tree (Ch 13.2.

Exam I Principles of Imperative Computation, Summer 2011 William Lovas. May 27, 2011

61A Lecture 6. Monday, February 2

CS240 Fall Mike Lam, Professor. Quick Sort

61A Lecture 7. Monday, September 15

Transcription:

CS 1110: Introduction to Computing Using Pyton Lecture 23 Sorting and Searcing [Andersen, Gries, Lee, Marscner, Van Loan, Wite]

Announcements Final Exam conflicts due tonigt at 11:59pm Final Exam review sessions on te 14 t Labs on 5/9 and 5/10 will be office ours Assignment 5 Due 11:59pm on ***Wednesday*** May 10 t Lab 13 is out 5/2/17 Sorting and Searcing 2

Recall: Accessing te Original Metod Wat if you want to use te original version metod? New metod = original+more Do not want to repeat code from te original version Call old metod explicitly Use metod as a function Pass object as first argument Example: Employee. str (self) class Employee(object): """An Employee wit a salary""" def str (self): return (self._name + ', year ' + str(self._start) + ', salary ' + str(self._salary)) class Executive(Employee): """An Employee wit a bonus.""" def str (self): return (Employee. str (self) + ', bonus ' + str(self._bonus)) 5/2/17 Sorting and Searcing 3

super Can also use super super(<class>, <instance>) returns te parent class of <class> and <instance> Example: super(executive, self). str () class Employee(object): """An Employee wit a salary""" def str (self): return (self._name + ', year ' + str(self._start) + ', salary ' + str(self._salary)) class Executive(Employee): """An Employee wit a bonus.""" def str (self): return (super(executive, self). str () + ', bonus ' + str(self._bonus)) 5/2/17 Sorting and Searcing 4

Dutc National Flag Variant Sequence of integer values red = negatives, wite = 0, blues = positive Only rearrange part of te list, not all pre: b? post: b < 0 = 0 > 0 t i j inv: b < 0? = 0 > 0 5/2/17 Sorting and Searcing 5

Dutc National Flag Variant Sequence of integer values red = negatives, wite = 0, blues = positive Only rearrange part of te list, not all pre: b? post: b < 0 = 0 > 0 t i j inv: b < 0? = 0 > 0 pre: t =, i = +1, j = post: t = i 5/2/17 Sorting and Searcing 6

Dutc National Flag Algoritm def dnf(b,, ): """Returns: partition points as a tuple (i,j)""" t = ; i = +1, j = ; # inv: b[..t-1] < 0, b[t..i-1]?, b[i..j] = 0, b[j+1..] > 0 wile t < i: if b[i-1] < 0: swap(b,i-1,t) t = t+1 elif b[i-1] == 0: i = i-1 else: swap(b,i-1,j) i = i-1 j = j-1 # post: b[..i-1] < 0, b[i..j] = 0, b[j+1..] > 0 return (i, j) 5/2/17 Sorting and Searcing < 0? = 0 > 0 t i j -1-2 3-1 0 0 0 6 3 t i j -1-2 3-1 0 0 0 6 3 t i j -1-2 -1 3 0 0 0 6 3 i t j -1-2 -1 0 0 0 3 6 3 7

Partition Algoritm Given a list segment b[..] wit some pivot value x in b[]: pre: b Swap elements of b[..] and store in i to trutify post: post: b cange: b x? i i+1 <= x x >= x 3 5 4 1 6 2 3 8 1 i into b 1 2 1 3 5 4 6 3 8 5/2/17 Sorting and Searcing 8

Sorting wit Partitions Given a list segment b[..] wit some value x in b[]: pre: b x? Swap elements of b[..] and store in j to trutify post: i i+1 post: b y <= y <= y? x >= y x >= x Partition Recursively Recursive partitions = sorting 5/2/17 Sorting and Searcing 11

QuicSort def quic_sort(b,, ): """Sort te array fragment b[..]""" if b[..] as fewer tan 2 elements: return i = partition(b,, ) # b[..i 1] <= b[i] <= b[i+1..] # Sort b[..i 1] and b[i+1..] quic_sort (b,, i 1) quic_sort (b, i+1, ) pre: b post: b x? i i+1 <= x x >= x 5/2/17 Sorting and Searcing 12

Linear Searc Vague: Find first occurrence of v in b[..-1]. Better: Store an integer in i to trutify result condition post: post: 1. v is not in b[..i-1] 2. i = OR v = b[i] 5/2/17 Sorting and Searcing 19

Linear Searc Vague: Find first occurrence of v in b[..-1]. Better: Store an integer in i to trutify result condition post: post: 1. v is not in b[..i-1] 2. i = OR v = b[i] pre: b? post: b i v not ere v? 5/2/17 Sorting and Searcing 20

Linear Searc Vague: Find first occurrence of v in b[..-1]. Better: Store an integer in i to trutify result condition post: post: 1. v is not in b[..i-1] 2. i = OR v = b[i] pre: b? post: b i v not ere v? OR b v not ere i 5/2/17 Sorting and Searcing 21

pre: b Linear Searc? post: b i v not ere v? OR b v not ere i inv: b i v not ere? 5/2/17 Sorting and Searcing 22

Linear Searc def linear_searc(b,v,,): """Returns: first occurrence of v in b[..-1]""" # Store in i index of te first v in b[..-1] i = # invariant: v is not in b[0..i-1] wile i < and b[i]!= v: i = i + 1 # post: v is not in b[..i-1] # i >= or b[i] == v return i if i < else -1 Analyzing te Loop 1. Does te initialization mae inv true? 2. Is post true wen inv is true and condition is false? 3. Does te repetend mae progress? 4. Does te repetend eep te invariant inv true? 5/2/17 Sorting and Searcing 23

Binary Searc Loo for v in sorted sequence segment b[..]. 5/2/17 Sorting and Searcing 24

Binary Searc Loo for v in sorted sequence segment b[..]. Precondition: b[..-1] is sorted (in ascending order). Postcondition: b[..i-1] < v and v <= b[i..] pre: b? post: b i < v >= v 5/2/17 Sorting and Searcing 25

Binary Searc Loo for value v in sorted segment b[..] pre: b post: b inv: b < v? i < v >= v i j? >= v Called binary searc because eac iteration of te loop cuts te array segment still to be processed in alf Example b 0 1 2 3 4 5 6 7 8 9 3 3 3 3 3 4 4 6 7 7 if v is 3, set i to 0 if v is 4, set i to 5 if v is 5, set i to 7 if v is 8, set i to 10 5/2/17 Sorting and Searcing 26

Binary Searc pre: b? i post: b < v >= v i j inv: b < v? >= v i = ; j = +1; wile i!= j: Looing at b[i] gives linear searc from left. Looing at b[j-1] gives linear searc from rigt. Looing at middle: b[(i+j)/2] gives binary searc. 5/2/17 Sorting and Searcing 27

Binary Searc def bsearc(b, v): i = 0 j = len(b) # invariant; b[0..i-1] < v, b[i..j-1] unnown, b[j..] >= v wile i < j: mid = (i+j)/2 if b[mid] < v: i = mid+1 else: #b[mid] >= v j = mid if i< len(b) and b[i] == v: else: return i return -1 Analyzing te Loop 1. Does te initialization mae inv true? 2. Is post true wen inv is true and condition is false? 3. Does te repetend mae progress? 4. Does te repetend eep te invariant inv true? 5/2/17 Sorting and Searcing 28

Binary Searc Recursive def rbsearc(b, v): """ len(b) > 0 """ return rbsearc_elper(b, v, 0, len(b)) def rbsearc_elper(b, v, i, j): if i >= j: if i < len(b) and b[i] == v: return i else: return -1 mid = (i + j) / 2 if b[mid] < v: return rbsearc_elper(b, v, mid + 1, j) else: # b[mid] >= v return rbsearc_elper(b, v, i, mid) 5/2/17 Sorting and Searcing 29