©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Sorting and Searching.

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 11 Sorting and Searching.
Advertisements

Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9: Searching, Sorting, and Algorithm Analysis
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
1 HeapSort CS 3358 Data Structures. 2 Heapsort: Basic Idea Problem: Arrange an array of items into sorted order. 1) Transform the array of items into.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
Chapter 11 Sorting and Searching. Topics Searching –Linear –Binary Sorting –Selection Sort –Bubble Sort.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
C++ Plus Data Structures
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Searching and Sorting Arrays
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Week 11 Sorting Algorithms. Sorting Sorting Algorithms A sorting algorithm is an algorithm that puts elements of a list in a certain order. We need sorting.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 10 Sorting and Searching.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
1 Data Structures and Algorithms Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus and Robert.
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Data Structures Using C++ 2E Chapter 10 Sorting Algorithms.
CSC 211 Data Structures Lecture 13
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Searching and Sorting.
CS1101: Programming Methodology
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
Chapter 12 Heaps & HeapSort © John Urrutia 2014, All Rights Reserved1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data,
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.
1 Heaps A heap is a binary tree. A heap is best implemented in sequential representation (using an array). Two important uses of heaps are: –(i) efficient.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Sorting and Searching. Searching  Problem definition: Given a value X, return the index of X in the array if such X exist. Otherwise, return NOT_FOUND(-1).
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Searching and Sorting Searching algorithms with simple arrays
Searching and Sorting Arrays
Decision Trees DEFINITION: DECISION TREE A decision tree is a tree in which the internal nodes represent actions, the arcs represent outcomes of an action,
Lecture 14 Searching and Sorting Richard Gesick.
Introduction to Search Algorithms
Bohyung Han CSE, POSTECH
Linear and Binary Search
Lecture 11 Searching and Sorting Richard Gesick.
Searching and Sorting Arrays
Standard Version of Starting Out with C++, 4th Edition
C++ Plus Data Structures
24 Searching and Sorting.
Algorithms: Design and Analysis
Searching and Sorting Arrays
Module 8 – Searching & Sorting Algorithms
EE 312 Software Design and Implementation I
Chapter 11 Sorting and Searching
Presentation transcript:

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Sorting and Searching

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Objectives After you have read and studied this chapter, you should be able to Perform linear and binary search algorithms on small arrays. Determine whether a linear or binary search is more effective for a given situation. Perform selection and bubble sort algorithms.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Objectives, cont. After you have read and studied this chapter, you should be able to Describe the heapsort algorithm and show how its performance is superior to that of the other two algorithms. Apply basic sorting algorithms to sort an array of objects, using the Comparator interface. Define the interface to specify common behavior and provide different versions of classes that implement the interface.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching Searching an array or other data structure has two possible outcomes: Successful search (value found) Unsuccessful search (value not found) It is possible for one searching algorithm to perform very well for successful searches, and very poorly for unsuccessful searches.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Figure 11.1 Successful and unsuccessful searches.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching We will examine two searching algorithms: Linear search Binary search A linear search searches the array from the first index position to the last in a linear progression. This search is also known as a sequential search.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching In a linear search, if the number of entries in the array is N, there will be N comparisons for an unsuccessful search. For a successful search, there will be a minimum of 1 and a maximum of N comparisons. On average, there will be N/2 comparisons.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching Below is a linear search algorithm. public int linearSearch (int[] number, int searchValue) { int loc = 0; while ( loc < number.length && number[loc] != searchValue) {loc++; } if ( loc == number.length) { //Not found return NOT_FOUND; } else { return loc;//Found, return the position }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching If the values in an array are arranged in ascending or descending order, the array is sorted. For a binary search to be applied, the array must be sorted. The idea behind the binary search is to divide the array elements in half each time, until the particular element is located.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching If we are searching for the value 77, we first find the middle position of the array. We see that 77 is not in index position [4].

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching We know the array is sorted. Since 77 is larger than 38, the value must be in the right half of the array. We next search the middle position of the right half of the array, which is index position [6], and locate the value.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Effect of one comparison in binary search.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching Using the binary search, in the worst case, the number of comparisons is the number of times you can divide the array in half. The maximum number of comparisons K is derived by solving the equation N = 2 K log 2 N = K

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching Below is a sample binary search method. public int binarySearch (int[] number, int searchValue) { int low = 0, high = number.length - 1, mid = (low + high) / 2; while (low <= high && number[mid] != searchValue ) { System.out.println(mid); if (number[mid] < searchValue) { low = mid + 1; }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Searching else { //number[mid] > searchValue high = mid - 1; } mid = (low + high) / 2; } if ( low > high) { mid = NOT_FOUND; } return mid; }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig How the unsuccessful search is terminated in the binary search routine.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Sorting Sorting is a technique to arrange elements in some order. We will examine three sorting algorithms: Selection sort Bubble sort Heapsort

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Sorting A natural sorting algorithm for a human looks like this: 1.Find the smallest integer in the list. 2.Cross out the number and copy it to a new sorted list. 3.Repeat steps 1 and 2 until all numbers in the list are crossed out.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Human sorting algorithm after three numbers are moved to the sorted list.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Sorting Selection sort is somewhat like the human approach. It finds the smallest number in a given list and moves it to the correct position in the list.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Sorting Selection sort is comprised of sorting passes. We locate the smallest element in the array and set the index min to point to this element. We then exchange number[start] and number[min]. After the first pass, the smallest element is moved to the correct position. We increase the value of start by 1 and execute the second pass.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Effect of executing the first pass in the selection sort.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Sorting We start the first pass with start = 0 and end the last pass with start = N-2.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Eight passes to sort the sample array of nine elements.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Sorting In selection sort, we make one data exchange per pass. In bubble sort, we make pairwise comparisons and exchange the pair if they are out of order.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Effect of executing the first pass in the bubble sort.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Sorting In the worst case, bubble sort will make N-1 passes, so its worst-case performance is the same as that of selection sort. Bubble sort exhibits two properties: After one pass through the array, the largest element will be at the end of the array. During one pass, if no pair of consecutive entries is out of order, then the array is sorted.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Sorting On average, we expect the bubble sort to finish sorting sooner than selection sort because there are more data movements for the same number of comparisons.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort The heapsort algorithm is generally much more efficient than either the bubble sort or the selection sort. The heapsort algorithm uses a special data structure called a heap.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort A heap consists of nodes, which contain data values, and edges, which link the nodes. The topmost node is called the root node of a heap. Nodes in a heap are indexed 0, 1, 2, and so on in top-to-bottom, left-to-right order.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A sample heap that includes nine nodes.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort A node in a heap has zero, one, or two children. The children of a node are distinguished as the node’s left or right children.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort A heap must satisfy two constraints: Structural constraint: Nodes in a heap with N nodes must occupy the positions numbered 0, 1,...,N-1. Value relationship constraint: A value stored in a node must be larger than the maximum of the values stored in its left and right children.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Sample heaps and nonheaps that violate the structural constraint.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Sample heaps and nonheaps that violate the value relationship constraint. Violations are indicated by blue ellipses.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort Heapsort is carried out in two phases: Construction phase: Construct a heap given N elements. Extraction phase: Pull out the value in the root successively, creating a new heap with one less element after each extraction step.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort If every node in the heap satisfies the value relationship constraint, then the value in the root node is the largest value in the heap. We then remove that value, and reconstruct a heap by moving the last element to the root position.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort We examine each node to confirm that both the structural and value relationship constraints are met. If the value relationship constraint is not met, we swap values until the relationship is satisfied. This swapping process is called a rebuild step.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig One rebuild step after the value 90 is pulled out of the heap. The net result of a single rebuild step is a new heap that contains one fewer element.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort In a heap of N elements, we can sort the N elements by performing the rebuild steps N-1 times. The array for the sorted list is filled from the end.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Eight rebuild steps to sort a heap with nine elements.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort We will examine the construction phase using the following unsorted numbers: 23, 17, 5, 90, 12, 44, 38, 84, 77 Assigning the numbers to a heap structure in ascending index order produces a heap that violates the value relationship constraint. The construction phase eliminates these violations.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A heap structure with given numbers assigned in ascending index order.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort The rebuild step is critical for constructing a heap. We build a heap in bottom-up fashion, starting small, and gradually building larger until all elements are contained in the heap.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig Sequence of rebuild steps applied in the construction phase.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort The array is one of the most effective data structures we can use to implement the heapsort in Java. With an array implementation, we can easily locate a given node’s left and right children. A node with index I has its left child at index 2I + 1 and its right child at index 2I + 2.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A sample heap and the corresponding array implementation.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort /* Chapter 11 Sample Program: Heap algorithm. File: Heap.java */ /** * Basic class for implementing the heapsort algorithm. * This class works only for integers. */ public class Heap { private int[ ] heap; private int[ ] sortedList; public Heap( ) { }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort // // Public Methods: // public void setData( int[ ] data ) { heap = new int[ data.length ]; sortedList = new int[ data.length ]; for (int i = 0; i < data.length; i++ ) { heap[i] = data[i]; } public int[] sort( ) { construct( ); //construction phase: construct the heap extract( ); //extraction phase: extract root nodes return sortedList; }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort // // Private Methods: // private void construct( ) { int current, maxChildIndex; boolean done; for (int i = (heap.length-2) / 2; i >= 0; i--) { current = i; done = false; while ( !done ) { if ( 2*current+1 > heap.length-1 ) { //current node has no children, so stop done = true; } else { //current node has at least one child, //get the index of larger child maxChildIndex = maxChild( current, heap.length-1 );

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort if ( heap[current] < heap[maxChildIndex] ) { swap( current, maxChildIndex ); current = maxChildIndex; } else { done = true; } assert isValidHeap(heap, i, heap.length-1): "Error: Construction phase is not working " + "correctly"; } //testPrint(heap.length); //TEMP } private boolean isValidHeap(int[] heap, int start, int end) { for (int i = 0; i < end/ 2; i++) { if (heap[i] < Math.max(heap[2*i+1], heap[2*i+2])){ return false; } return true; }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort private void extract( ) { int current, maxChildIndex; boolean done; for (int size = heap.length-1; size >= 0; size--) { //remove the root node data sortedList[size] = heap[ 0 ]; //move the last node to the root heap[ 0 ] = heap[size]; //rebuild current = 0; done = false; while ( !done ) { if ( 2*current+1 > size ) { //current node has no children, so stop done = true; } else { //current node has at least one child, //get the index of larger child maxChildIndex = maxChild( current, size );

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort if ( heap[current] < heap[maxChildIndex] ) { swap( current, maxChildIndex ); current = maxChildIndex; } else { //value relationship constraint //is satisfied, so stop done = true; } assert isValidHeap(heap, 0, size): "Error: Extraction phase is not working ” + “correctly"; //testPrint( size ); //TEMP }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort private int maxChild( int location, int end ) { int result, leftChildIndex, rightChildIndex; rightChildIndex = 2*location + 2; leftChildIndex = 2*location + 1; //Precondition: node at 'location' has at least //one child assert leftChildIndex <= end: "Error: node at position " + location + "has no children."; if ( rightChildIndex <= end && heap[leftChildIndex] < heap[rightChildIndex]) { result = rightChildIndex; } else { result = leftChildIndex; } return result; }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort private void swap ( int loc1, int loc2 ) { int temp; temp = heap[loc1]; heap[loc1] = heap[loc2]; heap[loc2] = temp; } private void testPrint( int limit ) { for (int i = 0; i < limit; i++) { System.out.print(" " + heap[i]); } System.out.println( " " ); }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort Bubble sort and selection sort perform roughly N 2 comparisons for sorting N elements. Heapsort performs roughly 1.5N log 2 N comparisons for sorting N elements.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display Heapsort The level of a node in a heap refers to the number of nodes in the path from the root to the node in question. The depth of a heap is defined to be the largest level of the nodes in the heap.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig A sample heap with depth = 4, which is defined to be the largest level of all nodes in a heap.