Chapter 9 Searching and Sorting

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Garfield AP Computer Science
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.
Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting Searching Event Processing Revisited File Choosers and.
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
Searching and Sorting Algorithms Based on D. S
The Quick Sort Textbook Authors: Ken Lambert & Doug Nance PowerPoint Lecture by Dave Clausen.
Chapter 19: Searching and Sorting Algorithms
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
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.
Lecture 25 Selection sort, reviewed Insertion sort, reviewed Merge sort Running time of merge sort, 2 ways to look at it Quicksort Course evaluations.
Searching and Sorting I 1 Searching and Sorting 1.
Chapter 11 Sorting and Searching. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Examine the linear search and.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
CHAPTER 11 Sorting.
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 Searching. 2 Introduction Searching is the process of finding a target element among a group of items (the search pool), or determining that.
Searching. 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 18 Searching and Sorting
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
1 Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L
Aalborg Media Lab 15-Jul-15 Polymorphism Lecture 12 Chapter 9.
Chapter 8 ARRAYS Continued
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Do Now Take out ch6 test answers – be ready to hand it in Pick a leader in each group of up to 3 students; Leader will retrieve a whiteboard, marker, and.
Building Java Programs Chapter 13 Searching reading: 13.3.
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.
Computer Science Searching & Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 8: Sorting and Searching Java Software Structures: Designing.
Chapter 9 – Part 2 Polymorphism: Sorting & 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.
COS 312 DAY 24 Tony Gauvin. Ch 1 -2 Agenda Questions? Last Capstone Progress reports over due Assignment 6 corrected – 2 A, 1 B, 1 C, 1 F and 2 MIA’s.
Searching and Sorting Chapter 18 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
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.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
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.
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.
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 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Searching and Sorting 14ACEHRPT Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Chapter 9 – Part 2 Polymorphism: Sorting & Searching.
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.
Sequential (Linear) Binary Selection** Insertion** Merge.
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
Chapter 9: Sorting and Searching Arrays
Searching and Sorting Algorithms
Sorting Mr. Jacobs.
Chapter 12 Recursion.
Ch 14: Search and Sorting Yonglei Tao.
Chapter 13: Searching and Sorting
Advanced Sorting Methods: Shellsort
Outline Late Binding Polymorphism via Inheritance
Sorting and Searching -- Introduction
Advanced Sorting Methods: Shellsort
Chapter 18 Searching and Sorting
Presentation transcript:

Chapter 9 Searching and Sorting Modified

Chapter Scope Generic Methods Search algorithms Sorting algorithms, including: Quicksort Merge sort Java Software Structures, 4th Edition, Lewis/Chase

Generic Methods A class that works on a generic type must be instantiated Since our methods will be static, we'll define each method to be a generic method A generic method header contains the generic type before the return type of the method: public static <T extends Comparable<T>> boolean binarySearch(T[] data, int min, int max, T target) Java Software Structures, 4th Edition, Lewis/Chase

Generic Methods The generic type can be used in the return type, the parameter list, and the method body Java Software Structures, 4th Edition, Lewis/Chase

Comparable We'll define the sorting algorithms such that they can sort any set of objects, therefore we will search objects that implement the Comparable interface Recall that the compareTo method returns an integer that specifies the relationship between two objects: obj1.compareTo(obj2) This call returns a number less than, equal to, or greater than 0 if obj1 is less than, equal to, or greater than obj2, respectively Java Software Structures, 4th Edition, Lewis/Chase

Searching Searching is the process of finding a target element among a group of items (the search pool), or determining that it isn't there Java Software Structures, 4th Edition, Lewis/Chase

Linear Search A linear search simply examines each item in the search pool, one at a time, until either the target is found or until the pool is exhausted This approach does not assume the items in the search pool are in any particular order Java Software Structures, 4th Edition, Lewis/Chase

/** * Searches the specified array of objects using linear search algorithm. * @param data the array to be searched * @param min the index of the first item in the array * @param max the index of the last item in the array * @param target the element being searched for * @return true if the desired element is found */ public static <T> boolean linearSearch(T[] data, int min, int max, T target) { int index = min; boolean found = false; while (!found && index <= max) found = data[index].equals(target); index++; } return found; Java Software Structures, 4th Edition, Lewis/Chase

Binary Search If the search pool must be sorted, then we can be more efficient than a linear search A binary search eliminates large parts of the search pool with each comparison Instead of starting the search at one end, we begin in the middle If the target isn't found, we know that if it is in the pool at all, it is in one half or the other We can then jump to the middle of that half, and continue similarly Java Software Structures, 4th Edition, Lewis/Chase

Binary Search A binary search algorithm is often implemented recursively Each recursive call searches a smaller portion of the search pool The base case is when the portion is of size 0 Java Software Structures, 4th Edition, Lewis/Chase

/** * Searches the specified array of objects using a binary search algorithm. * @param data the array to be searched * @param min the index of the first item in the portion to be searched * @param max the index of the last item in the portion to be searched * @param target the element being searched for * @return true if the desired element is found */ public static <T extends Comparable<T>> boolean binarySearch(T[] data, int min, int max, T target) { boolean found = false; int midpoint = (min + max) / 2; // determine the midpoint if (data[midpoint].compareTo(target) == 0) found = true; else if (data[midpoint].compareTo(target) > 0) if (min <= midpoint - 1) found = binarySearch(data, min, midpoint - 1, target); } else if (midpoint + 1 <= max) found = binarySearch(data, midpoint + 1, max, target); return found; Java Software Structures, 4th Edition, Lewis/Chase

Sorting Sorting is the process of arranging a group of items into a defined order based on particular criteria We must be able to compare one element to another Many sorting algorithms have been designed Sequential sorts require approximately n2 comparisons to sort n elements Logarithmic sorts typically require nlog2n comparisons to sort n elements Let's define a generic sorting problem that any of our sorting algorithms could help solve Java Software Structures, 4th Edition, Lewis/Chase

/. SortPhoneList driver for testing an object selection sort /** SortPhoneList driver for testing an object selection sort. */ public class SortPhoneList { /** * Creates an array of Contact objects, sorts them, & prints them. */ public static void main(String[] args) Contact[] friends = new Contact[7]; friends[0] = new Contact("John", "Smith", "610-555-7384"); friends[1] = new Contact("Sarah", "Barnes", "215-555-3827"); friends[2] = new Contact("Mark", "Riley", "733-555-2969"); friends[3] = new Contact("Laura", "Getz", "663-555-3984"); friends[4] = new Contact("Larry", "Smith", "464-555-3489"); friends[5] = new Contact("Frank", "Phelps", "322-555-2284"); friends[6] = new Contact("Marsha", "Grant", "243-555-2837"); Sorting.selectionSort(friends); for (Contact friend : friends) System.out.println(friend); } Java Software Structures, 4th Edition, Lewis/Chase

/. Contact represents a phone contact /** Contact represents a phone contact */ public class Contact implements Comparable<Contact> { private String firstName, lastName, phone; /** * Sets up this contact with the specified information. * @param first a string representation of a first name * @param last a string representation of a last name * @param telephone a string representation of a phone number */ public Contact(String first, String last, String telephone) firstName = first; lastName = last; phone = telephone; } Java Software Structures, 4th Edition, Lewis/Chase

/. Returns a description of this contact as a string /** Returns a description of this contact as a string. * @return a string representation of this contact */ public String toString() { return lastName + ", " + firstName + "\t" + phone; } /** Uses both last and first names to determine lexical ordering. * @param other the contact to be compared to this contact * @return the integer result of the comparison */ public int compareTo(Contact other) int result; if (lastName.equals(other.lastName)) result = firstName.compareTo(other.firstName); else result = lastName.compareTo(other.lastName); return result; Java Software Structures, 4th Edition, Lewis/Chase

Selection Sort Selection sort orders a list of values by repetitively putting a particular value into its final position Java Software Structures, 4th Edition, Lewis/Chase

/. Sorts the specified array using selection sort /** Sorts the specified array using selection sort * @param data the array to be sorted */ public static <T extends Comparable<T>> void selectionSort(T[] data) { int min; // Holds index of smallest element scanned in // inner loop for (int index = 0; index < data.length-1; index++) min = index; for (int scan = index+1; scan < data.length; scan++) if (data[scan].compareTo(data[min])<0) min = scan; swap(data, min, index); } Java Software Structures, 4th Edition, Lewis/Chase

/. Swaps 2 elements in an array. Used by various sorting algorithms /** * Swaps 2 elements in an array. * Used by various sorting algorithms. * * @param data the array in which the elements are swapped * @param index1 the index of the first element to be swapped * @param index2 the index of the second element to be swapped */ private static <T extends Comparable<T>> void swap(T[] data, int index1, int index2) { T temp = data[index1]; data[index1] = data[index2]; data[index2] = temp; } Java Software Structures, 4th Edition, Lewis/Chase

Quick Sort Quick sort orders values by partitioning the list around one element, then sorting each partition More specifically: choose one element in the list to be the partition (or pivot) element; we would like the pivot element to be the median value. organize the elements so that all elements less than the pivot element are to the left and all greater are to the right, with the pivot element between. apply the quick sort algorithm (recursively) to both partitions Java Software Structures, 4th Edition, Lewis/Chase

/** * Sorts the specified array of objects using the quick sort * algorithm. * * @param data the array to be sorted */ public static <T extends Comparable<T>> void quickSort(T[] data) { quickSort(data, 0, data.length - 1); } Java Software Structures, 4th Edition, Lewis/Chase

/. Recursively sorts a range of objects in the specified array /** * Recursively sorts a range of objects in the specified array * using the quick sort algorithm. * * @param data the array to be sorted * @param min the minimum index in the range to be sorted * @param max the maximum index in the range to be sorted */ private static <T extends Comparable<T>> void quickSort(T[] data, int min, int max) { if (min < max) // create partitions int indexofpartition = partition(data, min, max); // sort the left partition (lower values) quickSort(data, min, indexofpartition - 1); // sort the right partition (higher values) quickSort(data, indexofpartition + 1, max); } Java Software Structures, 4th Edition, Lewis/Chase

/. Used by the quick sort algorithm to find the partition /** * Used by the quick sort algorithm to find the partition. * * @param data the array to be sorted * @param min the minimum index in the range to be sorted * @param max the maximum index in the range to be sorted */ private static <T extends Comparable<T>> int partition(T[] data, int min, int max) { T partitionelement; // pivot element int left, right; // scanning indexes int middle = (min + max) / 2; // use the middle data value as the partition element partitionelement = data[middle]; // move it out of the way for now swap(data, middle, min); left = min; right = max; Java Software Structures, 4th Edition, Lewis/Chase

while (left < right) { // search for an element that is > the partition element while (left < right && data[left].compareTo(partitionelement) <= 0) left++; // Scan forward with left // search for an element that is <= the partition element while (data[right].compareTo(partitionelement) > 0) right--; // Scan backward with right // swap the elements if (left < right) swap(data, left, right); } // move the partition element into place swap(data, min, right); return right; Java Software Structures, 4th Edition, Lewis/Chase

Merge Sort Merge sort orders values by recursively dividing the list in half until each sub-list has one element, then recombining More specifically: divide the list into two roughly equal parts recursively divide each part in half, continuing until a part contains only one element merge the two parts into one sorted list continue to merge parts as the recursion unfolds Java Software Structures, 4th Edition, Lewis/Chase

Merge Sort Dividing lists in half repeatedly: Java Software Structures, 4th Edition, Lewis/Chase

Merge Sort Merging sorted elements Java Software Structures, 4th Edition, Lewis/Chase