©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 11 - 1 Chapter 11 Searching and Sorting.

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.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Visual C++ Programming: Concepts and Projects
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching with objects.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Chapter 11 Sorting and Searching. Topics Searching –Linear –Binary Sorting –Selection Sort –Bubble Sort.
Searching and Sorting I 1 Searching and Sorting 1.
Simple Sorting Algorithms
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Searching and Sorting with Objects.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Sorting and Searching.
Algorithm Efficiency and Sorting
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Searching Arrays Linear search Binary search small arrays
Searching and Sorting Arrays
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Chapter 8 ARRAYS Continued
© 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.
UNIT 18 Searching and Sorting.
Chapter 14 Searching and Sorting Section 1 - Sequential or Linear Search Section 2 - Binary Search Section 3 - Selection Sort Section 4 - Insertion Sort.
Applications of Arrays (Searching and Sorting) and Strings
1 Searching. 2 Searching Searching refers to the operation of finding an item from a list of items based on some key value. Two Searching Methods (1)
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
CS1101: Programming Methodology Aaron Tan.
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.
Data Structure Introduction.
Comparison-Based Sorting & Analysis Smt Genap
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.
CSCI 51 Introduction to Programming March 12, 2009.
3 – SIMPLE SORTING ALGORITHMS
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
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,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data,
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
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.
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).
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
Searching and Sorting Searching algorithms with simple arrays
Chapter 9: Sorting and Searching Arrays
Introduction to Search Algorithms
Recitation 13 Searching and Sorting.
Algorithm design and Analysis
Searching and Sorting 1-D Arrays
Chapter 11 Sorting and Searching
Presentation transcript:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Searching and Sorting

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data, we often need to quickly locate data Here’s the problem statement: Given a value X, return the index of X in the array, if such X exists. Otherwise, return NOT_FOUND (-1). We will look at two different algorithms. We will count the number of comparisons the algorithms make to analyze their performance. –The ideal searching algorithm will make the least possible number of comparisons to locate the desired data. –Two separate performance analyses are normally done, one for successful search and another for unsuccessful search.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Linear Search Search the array from the first to the last position in linear progression. 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 }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Linear Search Performance Count how many times the search value is compared against the array elements. –Analyze the successful and unsuccessful searches separately. Successful Search –Best Case = 1 comparison –Worst Case = N comparisons (N = array size)‏ Unsuccessful Search –Best Case = Worst Case = N comparisons

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Search Result number Unsuccessful Search: Successful Search: NOT_FOUND search( 45 )‏ search( 12 )‏ 4

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Binary Search If an array is sorted, then we can search faster using a binary search. The basic idea is straightforward. –First check the value in the middle position. –If X is less than this value, then search the left half next. –If X is greater than this value, then search the right half next. –Repeat the process until X is found or obviously not there. number

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Sequence of Successful Search search( 44 )‏ lowhighmid 0808 #1 high low 38 < 44 low = mid+1 = 5 mid 4

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Binary Search Routine public int binarySearch (int[] number, int searchValue) { int low = 0, high = number.length - 1, mid= (low + high) / 2; while (low <= high && number[mid] != searchValue) { if (number[mid] < searchValue) { low = mid + 1; } else { //number[mid] > searchValue high = mid - 1; } mid = (low + high) / 2; //integer division will truncate } if (low > high) { mid = NOT_FOUND; } return mid; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Binary Search Performance The section of an array to search is cut into half after every comparison –After K comparisons, there will be N/2 K elements in the list. –To get max number of comparisons, solve for K when N/2 K = 1 K = log 2 N. Successful Search –Best Case = 1 comparison –Worst Case = log 2 N comparisons Unsuccessful Search –Best Case = Worst Case = log 2 N comparisons

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Comparing N and log 2 N Performance Array SizeLinear O(N)Binary O(log 2 N)‏

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Sorting Often convenient to maintain a collection of data in sorted order –Data needs to be sorted to do a binary search –Example: arranging Person objects in order by age. Here’s the problem statement: Given an array of N integer values, arrange the values into ascending order. We will count the number of comparisons the algorithms make to analyze their performance. –The ideal sorting algorithm will make the least possible number of comparisons to arrange data in a designated order. We will compare different sorting algorithms by analyzing their worst-case performance.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Sort 1.Find the smallest element in the list. 2.Exchange the element in the first position and the smallest element. Now the smallest element is in the first position. 3.Repeat Step 1 and 2 with the list having one less element (i.e., the smallest element is discarded from further processing) min first exchange sorted unsorted This is the result of one pass.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Sort Passes sorted Pass # Result AFTER one pass is completed.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Sort Routine public void selectionSort(int[] number) { int startIndex, minIndex, length, temp; length = number.length; for (startIndex = 0; startIndex <= length-2; startIndex++){ //each iteration of the for loop is one pass minIndex = startIndex; //find the smallest in this pass at position minIndex for (int i = startIndex+1; i <= length-1; i++) { if (number[i] < number[minIndex]) minIndex = i; } //exchange number[startIndex] and number[minIndex] temp= number[startIndex]; number[startIndex] = number[minIndex]; number[minIndex] = temp; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Sort Performance We derive the total number of comparisons by counting the number of times the inner loop is executed. For each execution of the outer loop, the inner loop is executed length – start times. The variable length is the size of the array. Replacing length with N, the array size, the sum is derived as…

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Insertion Sort Exercise 5, page 660 Think of an array of numbers as consisting of a sorted part at the beginning and an unsorted part at the end –Initially, the sorted part is the first element –The unsorted part is the rest of the array While there are elements in the unsorted part –Take the first element of the unsorted part and insert it into the proper position in the sorted part

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Bubble Sort With the selection sort, we make one exchange at the end of one pass. The bubble sort improves the performance by making more than one exchange during its pass. By making multiple exchanges, we will be able to move more elements toward their correct positions using the same number of comparisons as the selection sort makes. The key idea of the bubble sort is to make pairwise comparisons and exchange the positions of the pair if they are out of order.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter One Pass of Bubble Sort The largest value 90 is at the end of the list exchange ok exchange

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Bubble Sort Routine public void bubbleSort(int[] number) { int temp, bottom, i; boolean exchanged = true; bottom = number.length - 2; while (exchanged) { exchanged = false; for (i = 0; i <= bottom; i++) { if (number[i] > number[i+1]) { temp = number[i]; //exchange number[i] = number[i+1]; number[i+1] = temp; exchanged = true; //exchange is made } bottom--; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Bubble Sort Performance In the worst case, the outer while loop is executed N-1 times for carrying out N-1 passes. For each execution of the outer loop, the inner loop is executed bottom+1 times. The number of comparisons in each successive pass is N-1, N-2, …, 1. Summing these will result in the total number of comparisons. So the performances of the bubble sort and the selection sort are approximately equivalent. However, on the average, the bubble sort performs much better than the selection sort because it can finish the sorting without doing all N-1 passes.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Where to find a sort method You don't have to write a sort method every time you need to sort an array The Arrays class from the java.util package has search and sort methods –binarySearch –sort (uses a faster sort method than the ones we looked at)‏ These methods are overloaded to work on arrays of any primitive type as well as arrays of objects

Searching Objects Similar to searching primitive arrays except you have several choices –Search for a particular object (by reference) in the array Compare using == –Search for a single object with a particular property or group of properties Match all the properties of a particular object using equals method Use accessor methods to get appropriate data for comparison –Search for all objects that meet search criterion Return an array (or collection) instead of a single object

Sorting Objects In order to sort objects of a particular type, we need a way to compare them –The relational operators ( = >) do not work with objects Two approaches to object comparison –Comparable interface The object class must implement the Comparable interface Class must define the method int compareTo( o) –Comparator interface Create a new class which implements the Comparator interface Need to define two methods int compare( o1, o2) boolean equals( Object o) // compare two Comparators

Comparable Interface Any class that implements Comparable must contain the method int compareTo( o)‏ Since it is inside the class, compareTo has access to all instance variables The Arrays class has a sort method that sorts Comparable objects –public static void sort (Comparable[] a)‏

Semantics of compareTo o1.compareTo( o2) returns –negative number if o1 comes before o2 –zero if o1 and o2 are the same –positive number if o1 comes after o2 For Strings –"abc".compareTo("bcd") is negative –"abc".compareTo("ABC") is positive –"abc".compareTo("abc") is 0

Comparator Interface Create a separate class whose sole purpose is to provide a comparison method int compare( o1, o2) Since it is a separate class, compareTo has to use accessor methods to get instance data The Arrays class has a sort method that sorts Comparable objects public static void sort (T[] a, Comparator c)‏

Semantics of compare ComparatorClass.compare ( o1, o2) returns –negative number if o1 comes before o2 –zero if o1 and o2 are the same –positive number if o1 comes after o2

Comparing Person Objects We define the Person class so we can compare Person objects by name or by age

Comparing Person Objects First, we need to determine how to compare Person objects The following does not make sense: Person p1 = …; Person p2 = …; if ( p1 < p2 ) { … }

Choosing an attribute to compare Modify the Person class to include a static variable that tells which attribute to compare. class Person implements Comparable { … public static final int NAME = 0; public static final int AGE = 1; public static int compareAttribute = NAME; … public static void setCompareAttribute(int attribute) { compareAttribute = attribute; public int compareTo( Object person){ …} } … }

The compareTo Method To compare Person objects, first set the comparison attribute and then call the compareTo Method. Person.setCompareAttribute (Person.NAME); int compResult = p1.compareTo(p2); if (compResult < 0) { //p1 “less than” p2 } else if (compResult == 0) { //p1 “equals” pw } else { //p2 “greater than” p2 } public int compareTo(Person p) { int compResult; if ( comparisonAttribute == AGE ) { int p2age = p.getAge(); if ( this.age < p2age ) { compResult = LESS; } … } else { //compare Name String p2Name = p.getName(); compResult = this.name. compareTo(p2Name); } return compResult; }

Using Comparators Implement the Comparator interface. We can define the implementation class so we can compare Person objects using any combination of their attributes –For example, we can define a comparator that compares Person objects by using both name and age

The AgeComparator Class This class compares the age attributes of Person objects public class AgeComparator implements Comparator { private final int LESS = -1; private final int EQUAL = 0; private final int MORE = 1; public int compare(Object p1, Object p2) { int comparisonResult; int p1age = ((Person)p1).getAge( ); int p2age = ((Person)p2).getAge( ); if (p1age < p2age) { comparisonResult = LESS; } else if (p1age == p2age) { comparisonResult = EQUAL; } else { assert p1age > p2age; comparisonResult = MORE; } return comparisonResult; }

The NameComparator Class This class compares the age attributes of Person objects Because the name attribute is a string we can use the compareTo method of the String class public class NameComparator implements Comparator { public int compare(Object p1, Object p2) { String p1name = ((Person)p1).getName( ); String p2name = ((Person)p2).getName( ); return p1name.compareTo(p2name); }

The NameComparator Class This class compares the age attributes of Person objects Because the name attribute is a string we can use the compareTo method of the String class public class NameComparator implements Comparator { public int compare(Person p1, Person p2) { String p1name = p1.getName( ); String p2name = p2.getName( ); return p1name.compareTo(p2name); }

The sort Method We use the sort method of the java.util.Arrays class public Person[ ] sort ( int attribute ) { if (!(attribute == Person.NAME || attribute == Person.AGE) ) { throw new IllegalArgumentException( ); } Person[ ] sortedList = new Person[ count ]; //copy references to sortedList for (int i = 0; i < count; i++) { sortedList[i] = entry[i]; } Arrays.sort(sortedList, getComparator(attribute)); return sortedList; }