Searching and Sorting Gary Wong.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Garfield AP Computer Science
Algorithms Analysis Lecture 6 Quicksort. Quick Sort Divide and Conquer.
Practice Quiz Question
Quick Sort, Shell Sort, Counting Sort, Radix Sort AND Bucket Sort
SORTING ROUTINES. OBJECTIVES INTRODUCTION BUBBLE SORT SELECTION SORT INSERTION SORT QUICK SORT MERGE SORT.
CPS120: Introduction to Computer Science Searching and Sorting.
Stephen P. Carl - CS 2421 Recursive Sorting Algorithms Reading: Chapter 5.
CMPS1371 Introduction to Computing for Engineers SORTING.
1 Sorting Problem: Given a sequence of elements, find a permutation such that the resulting sequence is sorted in some order. We have already seen: –Insertion.
CS203 Programming with Data Structures Sorting California State University, Los Angeles.
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
Sorting21 Recursive sorting algorithms Oh no, not again!
CHAPTER 11 Sorting.
Quicksort.
C++ Plus Data Structures
Chapter 7 (Part 2) Sorting Algorithms Merge Sort.
Searching and Sorting Arrays
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
Sorting HKOI Training Team (Advanced)
Computer Science 101 Fast Searching and Sorting. Improving Efficiency We got a better best case by tweaking the selection sort and the bubble sort We.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 19: Searching and Sorting Algorithms.
HKOI 2006 Intermediate Training Searching and Sorting 1/4/2006.
Chapter 10 B Algorithm Efficiency and Sorting. © 2004 Pearson Addison-Wesley. All rights reserved 9 A-2 Sorting Algorithms and Their Efficiency Sorting.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
1 Sorting Algorithms Sections 7.1 to Comparison-Based Sorting Input – 2,3,1,15,11,23,1 Output – 1,1,2,3,11,15,23 Class ‘Animals’ – Sort Objects.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
UNIT 5.  The related activities of sorting, searching and merging are central to many computer applications.  Sorting and merging provide us with a.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
ALGORITHMS.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Quicksort Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
Intro To Algorithms Searching and Sorting. Searching A common task for a computer is to find a block of data A common task for a computer is to find a.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Sorting Algorithms Written by J.J. Shepherd. Sorting Review For each one of these sorting problems we are assuming ascending order so smallest to largest.
INTRO2CS Tirgul 8 1. Searching and Sorting  Tips for debugging  Binary search  Sorting algorithms:  Bogo sort  Bubble sort  Quick sort and maybe.
Algorithm Design Techniques, Greedy Method – Knapsack Problem, Job Sequencing, Divide and Conquer Method – Quick Sort, Finding Maximum and Minimum, Dynamic.
Searching and Sorting Searching algorithms with simple arrays
Searching and Sorting Algorithms
CSCI 104 Sorting Algorithms
Lesson Objectives Aims Understand the following “standard algorithms”:
Parallel Sorting Algorithms
Sorting Algorithms Written by J.J. Shepherd.
Linear and Binary Search
Data Structures Review Session
Searching and Sorting Arrays
8/04/2009 Many thanks to David Sun for some of the included slides!
C++ Plus Data Structures
Parallel Sorting Algorithms
Divide and Conquer Algorithms Part I
Chapter 4.
Algorithm Efficiency and Sorting
CSE 373 Data Structures and Algorithms
Searching/Sorting/Searching
Core Assessments Core #1: This Friday (5/4) Core #2: Tuesday, 5/8.
Algorithm Efficiency and Sorting
Presentation transcript:

Searching and Sorting Gary Wong

Prerequisite Time complexity Pseudocode (Recursion)

Agenda Searching Sorting Linear (Sequential) Search Binary Search Bubble Sort Merge Sort Quick Sort Counting Sort

Linear Search One by one...

Linear Search Check every element in the list, until the target is found For example, our target is 38: i 1 2 3 4 5 a[i] 25 14 9 38 77 45 Not found! Found!

Linear Search Initilize an index variable i Compare a[i] with target If a[i]==target, found If a[i]!=target, If all have checked already, not found Otherwise, change i into next index and go to step 2

Linear Search Time complexity in worst case? Advantage? Disadvantage? If N is number of elements, Time complexity = O(N) Advantage? Disadvantage?

Binary Search Chop by half...

Binary Search Given a SORTED list: (Again, our target is 38) i 1 2 3 4 Smaller! Found! Larger! i 1 2 3 4 5 a[i] 9 14 25 38 45 77 L R

Binary Search Why always in the middle, but not other positions, say one-third of list? 1) Initialize boundaries L and R 2) While L is still on the left of R mid = (L+R)/2 If a[mid]>Target, set R be m-1 and go to step 2 If a[mid]<Target, set L be m+1 and go to step 2 If a[mid]==Target, found

Binary Search Time complexity in the worst case? Advantage? If N is the number of elements, Time complexity = O(lg N) Why? Advantage? Disadvantage?

Example: Three Little Pigs HKOI 2006 Final Senior Q1 Given three lists, each with M numbers, choose one number from each list such that their sum is maximum, but not greater than N. Constraints: M ≤ 3000 Time limit: 1s

Example: Three Little Pigs How many possible triples are there? Why not check them all? Time complexity? Expected score = 50

Example: Three Little Pigs A simpler question: How would you search for the maximum number in ONE SORTED list such that it is not greater than N? Binary search! With slight modification though How?

Example: Three Little Pigs Say, N=37 i 1 2 3 4 5 a[i] 9 14 25 38 45 77 L R

Example: Three Little Pigs Let’s go back to original problem If you have chosen two numbers a1[i] and a2[j] already, how would you search for the third number? Recall: How would you search for the maximum number in ONE SORTED list such that it is not greater than N-a1[i]-a2[j]?

Example: Three Little Pigs Overall time complexity? Expected score = 90 

Example: Three Little Pigs Slightly harder: Given TWO lists, each with M numbers, choose one number from each list such that their sum is maximum, but not greater than N. Linear search? Sort one list, then binary search! Time complexity = O(M lg M) O(M2) if less efficient sorting algorithm is used But, can it be better?

Example: Three Little Pigs Why is it so slow if we use linear search? If a1[i] and a2[j] are chosen, and their sum is smaller than N: Will you consider any number in a1 that is smaller than or equal a1[i]? If a1[i] and a2[j] are chosen, and their sum is greater than N: Will you consider any number in a2 that is greater than or equal to a2[j]?

Example: Three Little Pigs Recall: Why is it so slow if we use linear search? Because you use it for too many times! At which number in each list should you begin the linear search? Never look back at those we do not consider! Time complexity? Expected score = 100 

What can you learn? Improve one ‘dimension’ using binary search Linear search for a few times can be more efficient than binary search for many times! DO NOT underestimate linear search!!!

Points to note To use binary search, the list MUST BE SORTED (either ascending or decending) NEVER make assumptions yourself Problem setters usually do not sort for you Sorting is the bottleneck of efficiency But... how to sort?

How to sort? For C++: sort() Time complexity for sort() is O(N lg N) which is considered as efficient HOWEVER... Problem setters SELDOM test contestants on pure usage of efficient sorting algorithms Special properties of sorting algorithms are essential in problem-solving So, pay attention! 

Smaller? Float! Larger? Sink! Bubble Sort Smaller? Float! Larger? Sink!

Bubble Sort Suppose we need to sort in ascending order... Repeatedly check adjacent pairs sequentially, swap if not in correct order Example: The last number is always the largest 18 9 20 11 77 45 Incorrect order, swap! Correct order, pass!

Bubble Sort Fix the last number, do the same procedures for first N-1 numbers again... Fix the last 2 numbers, do the same procedures for first N-2 numbers again... ... Fix the last N-2 numbers, do the same procedures for first 2 numbers again...

Bubble Sort for i -> 1 to n-1 for j -> 1 to n-i if a[j]>a[j+1], swap them How to swap?

Many a little makes a mickle... Merge Sort & Quick Sort Many a little makes a mickle...

Merge Sort Now given two SORTED list, how would you ‘merge’ them to form ONE SORTED list? List 1: 8 14 22 List 2: 10 13 29 65 Temporary list: 8 8 10 10 13 13 14 14 22 22 29 29 65 65 Combined list:

Merge Sort Merge While both lists have numbers still not yet considered Compare the current first number in two lists Put the smaller number into temporary list, then discard it If list 1 is not empty, add them into temporary list If list 2 is not empty, add them into temporary list Put the numbers in temporary list back to the desired list

Merge Sort Suppose you are given a ‘function’ called ‘mergesort(L,R)’, which can sort the left half and right half of list from L to R: How to sort the whole list? Merge them! How can we sort the left and right half? Why not making use of ‘mergesort(L,R)’? 10 13 29 65 8 14 22 L (L+R)/2 (L+R)/2+1 R

Merge Sort mergesort(L,R){ If L is equal to R, done; Otherwise, } m=(L+R)/2; mergesort(L,M); mergesort(M+1,R); Merge the lists [L,M] and [M+1,R]; }

Merge Sort mergesort(0,6) mergesort(0,1) mergesort(2,3) mergesort(4,5) mergesort(6,6) 65 10 29 13 14 8 22 mergesort(0,0) mergesort(1,1) mergesort(2,2) mergesort(3,3) mergesort(4,4) mergesort(5,5) mergesort(0,3) mergesort(4,6) 8 10 10 13 10 65 29 13 13 14 65 29 22 8 8 29 14 14 65 22

Merge Sort Time complexity? O(N lg N) Why?

Quick Sort Choose a number as a ‘pivot’ Put all numbers smaller than ‘pivot’ on its left side Put all numbers greater than (or equal to) ‘pivot’ on its right side 10 13 29 65 8 14 22 10 13 8 14 22 65 29

a[y] < pivot! shift x, swap! Quick Sort a[y] < pivot! shift x, swap! How? y shifts to right by 1 unit in every round Check if a[y] < pivot If yes, shift x to right by 1 unit and swap a[x] and a[y] If y is at 2nd last position, swap a[x+1] and pivot Time complexity? 10 13 29 65 8 14 22 x y In fact, initial positions of x and y should be shifted to the left by 1 unit.

Quick Sort Use similar idea as in merge sort If we have a function called ‘quicksort(L,R)’... Make use of ‘quicksort(L,R)’ to sort the two halves! 10 13 8 14 22 65 29

Quick Sort quicksort(L,R){ If L is equal to R, done; Otherwise, } Choose a number as a pivot, say a[p]; Perform pivoting action; quicksort(L,p-1); quicksort(p+1,R); }

Quick Sort Time complexity in worst case? O(N2)  What is the worst case? Preventions: Choose a random number as pivot Pick 3 numbers, choose their median Under randomization, expected time complexity is O(N lg N)

Counting Sort No more comparison...

Counting Sort Create a list, then tally! Count the occurences of elements Example: Sort {2,6,1,4,2,1,9,6,4,1} in ascending order A list from 1 to 9 (or upper bound of input no.) Three ‘1’s, two ‘2’s, two ‘4’s, two ‘6’s and one ‘9’ List them all!

Counting Sort Time complexity? O(range * N) Good for numbers with small range

More... If we have time...

More... Lower bound of sorting efficiency?! Guess the answer by binary search Count the number of ‘inversions’ Find the kth largest number Other sorting algorithms

Time for lunch Yummy!