Searching & Sorting. Definitions of Search and Sort. Linear Search in C++ Linear Search. Week 11. index to the item, or -1 if not found.

Similar documents
Sequential search. Building Java Programs Chapter 13. Sequential search. Sequential search

CSCI 104 Sorting Algorithms. Mark Redekopp David Kempe

! 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.

Insertion Sort. Divide and Conquer Sorting. Divide and Conquer. Mergesort. Mergesort Example. Auxiliary Array

Sorting Review. Sorting. Comparison Sorting. CSE 680 Prof. Roger Crawfis. Assumptions

Today s Outline. Sorting: The Big Picture. Why Sort? Selection Sort: Idea. Insertion Sort: Idea. Sorting Chapter 7 in Weiss.

Sorting. Sorting. Why Sort? Consistent Ordering

CS240: Programming in C. Lecture 12: Polymorphic Sorting

CSE 326: Data Structures Quicksort Comparison Sorting Bound

CSE 326: Data Structures Quicksort Comparison Sorting Bound

CS1100 Introduction to Programming

More on Sorting: Quick Sort and Heap Sort

Sorting: The Big Picture. The steps of QuickSort. QuickSort Example. QuickSort Example. QuickSort Example. Recursive Quicksort

! 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.

Sorting. Sorted Original. index. index

Quicksort. Part 1: Understanding Quicksort

Sorting and Algorithm Analysis

! 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.

Problem Set 3 Solutions

Course Introduction. Algorithm 8/31/2017. COSC 320 Advanced Data Structures and Algorithms. COSC 320 Advanced Data Structures and Algorithms

CE 221 Data Structures and Algorithms

Programming in Fortran 90 : 2017/2018

Design and Analysis of Algorithms

Kent State University CS 4/ Design and Analysis of Algorithms. Dept. of Math & Computer Science LECT-16. Dynamic Programming

Exercises (Part 4) Introduction to R UCLA/CCPR. John Fox, February 2005

Brave New World Pseudocode Reference

CS221: Algorithms and Data Structures. Priority Queues and Heaps. Alan J. Hu (Borrowing slides from Steve Wolfman)

Parallel Numerics. 1 Preconditioning & Iterative Solvers (From 2016)

Terminal Window. 11. Section 7 Exercises Program Memory Exercise 7-1 Swap Values in an Array Working memory Global Memory. 2 nd call 3 rd call

Algorithm To Convert A Decimal To A Fraction

Non-Split Restrained Dominating Set of an Interval Graph Using an Algorithm

CHAPTER 10: ALGORITHM DESIGN TECHNIQUES

ELEC 377 Operating Systems. Week 6 Class 3

Chapter 10 Sorting and Searching Algorithms

Priority queues and heaps Professors Clark F. Olson and Carol Zander

Harvard University CS 101 Fall 2005, Shimon Schocken. Assembler. Elements of Computing Systems 1 Assembler (Ch. 6)

Machine Learning: Algorithms and Applications

Reading. 14. Subdivision curves. Recommended:

CMPS 10 Introduction to Computer Science Lecture Notes

Ch 8. Searching and Sorting Arrays Part 1. Definitions of Search and Sort

Chapter 10. Sorting and Searching Algorithms. Fall 2017 CISC2200 Yanjun Li 1. Sorting. Given a set (container) of n elements

We can use a max-heap to sort data.

Performance Evaluation of Information Retrieval Systems

Machine Learning. Topic 6: Clustering

News. Recap: While Loop Example. Reading. Recap: Do Loop Example. Recap: For Loop Example

6.854 Advanced Algorithms Petar Maymounkov Problem Set 11 (November 23, 2005) With: Benjamin Rossman, Oren Weimann, and Pouya Kheradpour

Sorting. Task Description. Selection Sort. Should we worry about speed?

Array transposition in CUDA shared memory

Assembler. Shimon Schocken. Spring Elements of Computing Systems 1 Assembler (Ch. 6) Compiler. abstract interface.

Load Balancing for Hex-Cell Interconnection Network

Lecture 6 Sorting and Searching

COMP 250. Lecture 7. Sorting a List: bubble sort selection sort insertion sort. Sept. 22, 2017

Compiler Design. Spring Register Allocation. Sample Exercises and Solutions. Prof. Pedro C. Diniz

1 Dynamic Connectivity

AMath 483/583 Lecture 21 May 13, Notes: Notes: Jacobi iteration. Notes: Jacobi with OpenMP coarse grain

Parallelism for Nested Loops with Non-uniform and Flow Dependences

Sorting Algorithms. + Analysis of the Sorting Algorithms

O n processors in CRCW PRAM

A New Exact Algorithm for Traveling Salesman Problem with Time Complexity Interval (O(n^4), O(n^3 2^n))

SCJ2013 Data Structure & Algorithms. Bubble Sort. Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi

Report on On-line Graph Coloring

Dijkstra s Single Source Algorithm. All-Pairs Shortest Paths. Dynamic Programming Solution. Performance. Decision Sequence.

1 a = [ 5, 1, 6, 2, 4, 3 ] 4 f o r j i n r a n g e ( i + 1, l e n ( a ) 1) : 3 min = i

An Optimal Algorithm for Prufer Codes *

Assignment # 2. Farrukh Jabeen Algorithms 510 Assignment #2 Due Date: June 15, 2009.

Support Vector Machines

LOOP ANALYSIS. The second systematic technique to determine all currents and voltages in a circuit

Intro. Iterators. 1. Access

Hierarchical clustering for gene expression data analysis

Efficient Distributed File System (EDFS)

Gaussian elimination. System of Linear Equations. Gaussian elimination. System of Linear Equations

Module Management Tool in Software Development Organizations

9. BASIC programming: Control and Repetition

CS434a/541a: Pattern Recognition Prof. Olga Veksler. Lecture 15

Efficient Multidimensional Searching Routines for Music Information Retrieval

5 The Primal-Dual Method

Programming II (CS300)

Sorting is ordering a list of objects. Here are some sorting algorithms

The Greedy Method. Outline and Reading. Change Money Problem. Greedy Algorithms. Applications of the Greedy Strategy. The Greedy Method Technique

Bayesian Networks: Independencies and Inference. What Independencies does a Bayes Net Model?

Esc101 Lecture 1 st April, 2008 Generating Permutation

Problem. Input: An array A = (A[1],..., A[n]) with length n. Output: a permutation A of A, that is sorted: A [i] A [j] for all. 1 i j n.

Searching and Sorting

Module 08: Searching and Sorting Algorithms

Divide and Conquer Algorithms: Advanced Sorting. Prichard Ch. 10.2: Advanced Sorting Algorithms

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm

Outline. Type of Machine Learning. Examples of Application. Unsupervised Learning

CHAPTER 2 DECOMPOSITION OF GRAPHS

CS 534: Computer Vision Model Fitting

Data Structures and Algorithms for Engineers

Inverse Kinematics (part 2) CSE169: Computer Animation Instructor: Steve Rotenberg UCSD, Spring 2016

Solutions to Programming Assignment Five Interpolation and Numerical Differentiation

R s s f. m y s. SPH3UW Unit 7.3 Spherical Concave Mirrors Page 1 of 12. Notes

Chapter 10 - Notes Applications of Arrays

Overview. CSC 2400: Computer Systems. Pointers in C. Pointers - Variables that hold memory addresses - Using pointers to do call-by-reference in C

Lecture #15 Lecture Notes

ON SOME ENTERTAINING APPLICATIONS OF THE CONCEPT OF SET IN COMPUTER SCIENCE COURSE

High level vs Low Level. What is a Computer Program? What does gcc do for you? Program = Instructions + Data. Basic Computer Organization

Real-Time Guarantees. Traffic Characteristics. Flow Control

A Comparison of Top-k Temporal Keyword Querying over Versioned Text Collections

Transcription:

Searchng & Sortng Wee 11 Gadds: 8, 19.6,19.8 CS 5301 Sprng 2014 Jll Seaman 1 Defntons of Search and Sort Search: fnd a gven tem n a lst, return the ndex to the tem, or -1 f not found. Sort: rearrange the tems n an array nto some order (smallest to bggest, alphabetcal order, etc.). There are varous methods (algorthms) for carryng out these common tass. 2 Lnear Search Lnear Search n C++ Very smple method. Compare frst element to target value, f not found then compare second element to target value... Repeat untl: target value s found (return ts ndex) or we run out of tems (return -1). nt searchlst (nt lst[], nt sze, nt value) { nt ndex=0; nt poston = -1; bool found = false; //ndex to process the array //poston of target //flag, true when target s found whle (ndex < sze && found) { f (lst[ndex] == value) //found the target { found = true; //set the flag poston = ndex; //record whch tem ndex++; //ncrement loop ndex return poston; 3 4

Lnear Search n C++ smplfed Other forms of Lnear Search nt searchlst (nt lst[], nt sze, nt value) { for (nt =0; <sze; ++) { f (lst[] == value) return ; return -1; Recursve lnear search over arrays See Lab 10, exercse #1: smember functon Lnear search over lned lst A good exercse (Gadds ch 17 Prog Challenge #5) Recursve lnear search over lned lst Another good exercse 5 6 Bnary Search Wors only for SORTED arrays Dvde and conquer style algorthm Compare target value to mddle element n lst. f equal, then return ts ndex f less than mddle element, repeat the search n the frst half of lst f greater than mddle element, repeat the search n last half of lst If current search lst s narrowed down to 0 elements, return -1 7 target s 11 target < 50 target > 7 Bnary Search Algorthm example target == 11 frst frst frst last last last 8

Bnary Search n C++ teratve verson nt bnarysearch (nt array[], nt sze, nt target) { nt frst = 0, last = sze 1, mddle, poston = -1; bool found = false; whle (frst <= last && found) { mddle = (frst + last) /2; //ndex to (current) frst elem //ndex to (current) last elem //ndex of (current) mddle elem //ndex of target value //flag //calculate mdpont f (array[mddle] == target) { found = true; poston = mddle; else f (target < array[mddle]) { last = mddle 1; //search lower half else { frst = mddle + 1; return poston; //search upper half 9 Bnary Search n C++ Recursve verson nt bnarysearchrec(nt array[], nt frst, nt last, nt value) { nt mddle; // Md pont of search f (frst > last) //chec for empty lst return -1; mddle = (frst + last)/2; //compute mddle ndex f (array[mddle]==value) return mddle; f (value < array[mddle]) //recurson return bnarysearchrec(array, frst,mddle-1, value); else return bnarysearchrec(array, mddle+1,last, value); nt bnarysearch(nt array[], nt sze, nt value) { return bnarysearchrec(array, 0, sze-1, value); 10 What s sortng? Sort: rearrange the tems n a lst nto ascendng or descendng order - numercal order - alphabetcal order - etc. 55 112 78 14 20 179 42 67 190 7 101 1 122 170 8 Sortng algorthms Bubble sort Merge sort Qucsort 1 7 8 14 20 42 55 67 78 101 112 122 170 179 190 11 12

On each pass: Bubble sort - Compare frst two elements. If the frst s bgger, they exchange places (swap). - Compare second and thrd elements. If second s bgger, exchange them. - Repeat untl last two elements of the lst are compared. Repeat ths process untl a pass completes wth no exchanges 13 Bubble sort how does t wor? At the end of the frst pass, the largest element s moved to the end (t s bgger than all ts neghbors) At the end of the second pass, the second largest element s moved to ust before the last element. The bac end (tal) of the lst remans sorted. Each pass ncreases the sze of the sorted porton. No exchanges mples each element s smaller than ts next neghbor (so the lst s sorted). 14 Bubble sort 7 2 3 8 9 1 7 > 2, swap 2 7 3 8 9 1 7 > 3, swap 2 3 7 8 9 1 (7 > 8), no swap 2 3 7 8 9 1 (8 > 9), no swap 2 3 7 8 9 1 9 > 1, swap 2 3 7 8 1 9 fnshed pass 1, dd 3 swaps Note: largest element s n last poston Bubble sort 2 3 7 8 1 9 2<3<7<8, no swap, (8<1), swap 2 3 7 1 8 9 (8<9) no swap fnshed pass 2, dd one swap 2 3 7 1 8 9 2<3<7, no swap, (7<1), swap 2 3 1 7 8 9 7<8<9, no swap fnshed pass 3, dd one swap 2 largest elements n last 2 postons 3 largest elements n last 3 postons 15 16

Bubble sort 2 3 1 7 8 9 2<3, (3<1) swap, 3<7<8<9 2 1 3 7 8 9 fnshed pass 4, dd one swap 2 1 3 7 8 9 (2<1) swap, 2<3<7<8<9 1 2 3 7 8 9 fnshed pass 5, dd one swap 1 2 3 7 8 9 1<2<3<7<8<9, no swaps fnshed pass 6, no swaps, lst s sorted 17 Bubble sort: code template<class ItemType> vod bubblesort (ItemType a[], nt sze) { bool swapped; do { swapped = false; for (nt = 0; < (sze-1); ++) { f (a[] > a[+1]) { swap(a[],a[+1]); swapped = true; whle (swapped); 18 Merge sort Dvde and conquer 2 half-szed lsts sorted recursvely the algorthm: - f lst sze s 0 or 1, return (base case) otherwse: - recursvely sort frst half and then second half of lst. - merge the two sorted halves nto one sorted lst. 19 Merge sort Recursvely dvde lst n half: - call mergesort recursvely on each one. 5 2 4 6 1 3 2 6 5 2 4 6 1 3 2 6 5 2 4 6 1 3 2 6 5 2 4 6 1 3 2 6 Each of these are sorted (base case length = 1) 20

Merge sort Calls to merge, startng from the bottom: Merge sort Mergng How to merge 2 (adacent) lsts: values temp frst mddle last 21 1 1 2 1 2 13 compare values[] to values[], copy smaller to temp[] 22 values Contnued: Merge sort Mergng temp 1 2 13 15 Now ==mddle+1 Now ==last+1 1 2 13 15 24 1 2 13 15 24 26 1 2 13 15 24 26 27 1 2 13 15 24 26 27 38 copy temp to values Merge sort: code vod mergesortrec (double values[], nt frst, nt last) { f (frst < last) { nt mddle = (frst + last) / 2; mergesortrec(values, frst, mddle); mergesortrec(values, mddle+1, last); merge(values, frst, mddle, last); vod mergesort (double values[], nt sze) { mergesortrec(values, 0, sze-1); 24

Merge sort: code: merge vod merge(double values[], nt frst, nt mddle, nt last) { double *tmp = new double[last-frst+1]; //temporary array nt =frst; //ndex for left nt =mddle+1; //ndex for rght nt =0; //ndex for tmp whle (<=mddle && <=last) //merge, compare next elem from each array f (values[] < values[]) tmp[++] = values[++]; else tmp[++] = values[++]; whle (<=mddle) //merge remanng elements from left, f any tmp[++] = values[++]; whle (<=last) //merge remanng elements from rght, f any tmp[++] = values[++]; for (nt = frst; <=last; ++) //copy from tmp array bac to values values[] = tmp[-frst]; 25 delete [] tmp; //deallocate temp array Quc sort Another dvde and conquer 2 (hopefully) half-szed lsts sorted recursvely the algorthm: - If lst sze s 0 or 1, return. otherwse: - partton nto two lsts: pc one element as the pvot put all elements less than pvot n frst half put all elements greater than pvot n second half - recursvely sort frst half and then second half of lst. 26 Qucsort Qucsort cont. 27 28

Qucsort: parttonng Goal: partton a sub-array A [start...end] by rearrangng the elements and returnng the ndex of the pvot pont p so that: - A[x]<=A[p] for x<p and A[x]>=A[p] for x>p the algorthm: - pc a pvot value and swap wth start elem - let = start and = start +1 4 8 5 6 3 19 12 6 8 5 4 3 19 12 Qucsort: parttonng use to terate over the lst elements - whenever set[] < the pvot value (6): a. ncrement and then b. swap set[] wth set[]. 6 8 5 4 3 19 6 5 8 4 3 19 12 6 5 8 4 3 19 12 12 6 5 4 8 3 19 12 Ths mantans: A[x]<=A[] for x<=, (All elements left of are <= 6) pvot 29 30 the algorthm (contnued): Qucsort: parttonng 6 5 4 8 3 19 12 6 5 4 3 8 19 12 - then, after the, swap start wth, and return 6 5 4 3 8 19 12 3 5 4 6 8 19 12 Note: s not always the mdpont 31 Qucsort: code vod qucsort(nt set[], nt start, nt end) { f (start < end) { // Get the pvot pont. nt pvotpont = partton(set, start, end); // Sort the frst sub lst. qucsort(set, start, pvotpont - 1); // Sort the second sub lst. qucsort(set, pvotpont + 1, end); vod qucsort (nt set[], nt sze) { qucsort(set, 0, sze-1); 32

Qucsort: code nt partton(nt set[], nt start, nt end) { nt md = (start + end) / 2; // locate the pvot value swap(set[start], set[md]); nt = start; nt pvotvalue = set[start]; for (nt = start + 1; <= end; ++) { // fnds values less than pvotvalue and // moves them to the left of the f (set[] < pvotvalue) { ++; swap(set[], set[]); swap(set[start], set[]); return ; 33