1 Programming for Engineers in Python Autumn 2011-12 Lecture 9: Sorting, Searching and Time Complexity Analysis.

Slides:



Advertisements
Similar presentations
College of Information Technology & Design
Advertisements

Introduction to Computer Science Theory
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
HST 952 Computing for Biomedical Scientists Lecture 10.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
 1 Sorting. For computer, sorting is the process of ordering data. [ ]  [ ] [ “Tom”, “Michael”, “Betty” ]  [ “Betty”, “Michael”,
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
Advanced Topics in Algorithms and Data Structures Lecture 6.1 – pg 1 An overview of lecture 6 A parallel search algorithm A parallel merging algorithm.
Fall 2006CENG 7071 Algorithm Analysis. Fall 2006CENG 7072 Algorithmic Performance There are two aspects of algorithmic performance: Time Instructions.
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
Recursion. Binary search example postponed to end of lecture.
E.G.M. Petrakissorting1 Sorting  Put data in order based on primary key  Many methods  Internal sorting:  data in arrays in main memory  External.
Data Structures Performance Analysis.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (3) Recurrence Relation 11/11 ~ 11/14/2008 Yang Song.
Searching Arrays Linear search Binary search small arrays
Analysis of Algorithm.
Lecture 3 Feb 7, 2011 Goals: Chapter 2 (algorithm analysis) Examples: Selection sorting rules for algorithm analysis Image representation Image processing.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search -Reading p
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
CS Discrete Mathematical Structures Mehdi Ghayoumi MSB rm 132 Ofc hr: Thur, 9:30-11:30a.
COMP s1 Computing 2 Complexity
Recursion, Complexity, and Searching and Sorting By Andrew Zeng.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Chapter 19 Searching, Sorting and Big O
CHAPTER 09 Compiled by: Dr. Mohammad Omar Alhawarat Sorting & Searching.
Recursion, Complexity, and Sorting By Andrew Zeng.
Nattee Niparnan. Recall  Complexity Analysis  Comparison of Two Algos  Big O  Simplification  From source code  Recursive.
Chapter 12 Recursion, Complexity, and Searching and Sorting
Analysis of Algorithms
1 Lecture 16: Lists and vectors Binary search, Sorting.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 9: Algorithm Efficiency and Sorting Data Abstraction &
Complexity of algorithms Algorithms can be classified by the amount of time they need to complete compared to their input size. There is a wide variety:
SEARCHING UNIT II. Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two or more smaller instances.
Merge Sort. What Is Sorting? To arrange a collection of items in some specified order. Numerical order Lexicographical order Input: sequence of numbers.
Algorithm Evaluation. What’s an algorithm? a clearly specified set of simple instructions to be followed to solve a problem a way of doing something What.
© 2011 Pearson Addison-Wesley. All rights reserved 10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
1 Searching and Sorting Linear Search Binary Search.
 2005 Pearson Education, Inc. All rights reserved Searching and Sorting.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
SEARCHING. Vocabulary List A collection of heterogeneous data (values can be different types) Dynamic in size Array A collection of homogenous data (values.
CMPT 438 Algorithms. Why Study Algorithms? Necessary in any computer programming problem ▫Improve algorithm efficiency: run faster, process more data,
CSC 211 Data Structures Lecture 13
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
New Mexico Computer Science For All Algorithm Analysis Maureen Psaila-Dombrowski.
Sorting: Implementation Fundamental Data Structures and Algorithms Klaus Sutner February 24, 2004.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Sorting and Searching by Dr P.Padmanabham Professor (CSE)&Director
קורס תכנות שיעור עשירי: מיונים, חיפושים, וקצת סיבוכיות חישוב.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Searching Topics Sequential Search Binary Search.
1 Ch. 2: Getting Started. 2 About this lecture Study a few simple algorithms for sorting – Insertion Sort – Selection Sort (Exercise) – Merge Sort Show.
Search Algorithms Written by J.J. Shepherd. Sequential Search Examines each element one at a time until the item searched for is found or not found Simplest.
Today’s Material Sorting: Definitions Basic Sorting Algorithms
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
1 Algorithms Searching and Sorting Algorithm Efficiency.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Assignment 5 is posted. Exercise 8 is very similar to what you will be doing with assignment 5. Exam.
CMPT 438 Algorithms.
COP 3503 FALL 2012 Shayan Javed Lecture 15
שיעור עשירי: מיונים, חיפושים, וקצת סיבוכיות חישוב
Teach A level Computing: Algorithms and Data Structures
Searching.
Presentation transcript:

1 Programming for Engineers in Python Autumn Lecture 9: Sorting, Searching and Time Complexity Analysis

Design a recursive algorithm by 1. Solving big instances using the solution to smaller instances 2. Solving directly the base cases Recursive algorithms have 1. Stopping criteria 2. Recursive case(s) 3. Construction of a solution using solution to smaller instances 2 Lecture 8: Highlights

3 Today Information Importance of quick access to information How can it be done? Preprocessing the data enables fast access to what we are interested in Example: dictionary The most basic data structure in Python: list Sorting  preprocessing Searching  fast access Time complexity

Information 4 There are about 20,000,000,000 web pages in the internet

Sorting A sorted array is an array whose values are in ascending/descending order Very useful Sorted array example: Super easy in Python – the sorted function

Why is it Important to Sort Information? To find a value, and fast! Finding M values in a list of size N Naive solution: given a query, traverse the list and find the value Not efficient, average of N/2 operations per query Better: sort the array once and than perform each query much faster 6

Why not Use Dictionaries? Good idea! Not appropriate for all applications: Find the 5 most similar results to the query Query's percentile We will refer to array elements of the form (key, value) 7

Naïve Search in a General Array Find location of a value in a given array 8

Binary Search (requires a sorted array) 9 Input: sorted array A, query k Output: corresponding value / not found Algorithm: Check the middle element in A If the corresponding key equals k return corresponding value If k < middle find k in A[0:middle-1] If k > middle find k in A[middle+1:end]

10 Example value index Searching for 56

11 Example value index Searching for 4

12 Code –Binary Search

13 Binary Search – 2 nd Try

Time Complexity 14 Worst case: Array size decreases with every recursive call Every step is extremely fast (constant number of operations - c) There are at most log 2 (n) steps Total of approximately c*log 2 (n) For n = 1,000,000 binary search will take 20 steps - much faster than the naive search

Time Complexity על רגל אחת 15 Algorithms complexity is measured by run time and space (memory) Ignoring quick operations that execute constant number of times (independent of input size) Approximate time complexity in order of magnitude, denoted with O ( Example: n = 1,000,000 O(n 2 ) = constant * trillion (Tera) O(n) = constant * million (Mega) O(log 2 (n)) = constant * 20

16 Order of Magnitude nlog 2 nn log 2 nn2n ,04865,536 4, ,15216,777,216 65, ,048,5654,294,967,296 1,048, ,971,5201,099,511,627,776 16,777, ,653,183281,474,976,710,656

Graphical Comparison 17

18 Code – Iterative Binary Search

19 Testing Efficiency Preparations (Tutorial for timeit:

20 Testing Efficiency

21 Results

Until now we assumed that the array is sorted… 22 How to sort an array efficiently?

Bubble Sort מיון בועות 23 נסרוק את המערך ונשווה כל זוג ערכים שכנים נחליף ביניהם אם הם בסדר הפוך נחזור על התהליך עד שלא צריך לבצע יותר החלפות (המערך ממויין) למה בועות? האלגוריתם "מבעבע" בכל סריקה את האיבר הגדול ביותר למקומו הנכון בסוף המערך.

(done) Bubble Sort Example

25 Code – Bubble Sort n iterations i iterations constant (n-1 + n-2 + n-3 + …. + 1) * const ~ ½ * n 2

26 דוגמאות לחישוב סיבוכיות זמן ריצה מצא ערך מקסימלי במערך לא ממויין מצא ערך מקסימלי במערך ממויין מצא את הערך החמישי הכי גדול במערך ממויין מצא ערך מסויים במערך לא ממויין מצא ערך מסויים במערך ממויין ענה על n " שאלות פיבונאצ ' י " שאלת פיבונאצ ' י : מהו הערך ה -K בסדרת פיבונאצ ' י ? נניח ש -K מוגבל להיות קטן מ -MAX

We showed that it is possible to sort in O(n 2 ) Can we do it faster? 27 Yes! – Merge Sort

28 Comparing Bubble Sort with sorted

The Idea Behind Merge Sort 29 Sorting a short array is much faster than a long array Two sorted arrays can be merged to a combined sorted array quite fast (O(n))

Generic Sorting 30 We would like to sort all kinds of data types Ascending / descending order What is the difference between the different cases? Same algorithm! Are we required to duplicate the same algorithm for each data type?

The Idea Behind Generic Sorting Write a single function that will be able to sort all types in ascending and descending order What are the parameters? The list Ascending/descending order A comparative function 31