Sorting and Searching

Similar documents
Sorting & Searching (and a Tower)

Sorting/Searching and File I/O

Searching and Sorting (Savitch, Chapter 7.4)

What is an algorithm?

ECM1406. Answer Sheet Lists

1. Download the JDK 6, from

Exercise 4: Loops, Arrays and Files

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

Classes Basic Overview

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

Unit 10: Sorting/Searching/Recursion

4. Finding & Displaying Record of Salesman with minimum net income. 5. Finding & Displaying Record of Salesman with maximum net income.

Sorting/Searching and File I/O. Sorting Searching Reading for this lecture: L&L

Lab 11. A sample of the class is:

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371

Lecture #8-10 Arrays

University of Palestine. Mid Exam Total Grade: 100

H212 Introduction to Software Systems Honors

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm

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

Recursion. General Algorithm for Recursion. When to use and not use Recursion. Recursion Removal. Examples

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

A Guide Illustrating the Core Java Equivalent to Selected Tasks Done Using the HSA Class Library

20 Standard API: Math: round() 21 Salary analysis 22 Standard API: System: out.printf(): string item 24 Standard API: System: out.printf(): fixed text

CSC 1051 Data Structures and Algorithms I

CIS 110: Introduction to computer programming

Topics. Sorting. Sorting. 1) How can we sort data in an array? a) Selection Sort b) Insertion Sort

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Selection Statements and operators

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

Course Content. Objectives of Lecture 18 Black box testing and planned debugging. Outline of Lecture 18

Assignment2013 Please use this document only for verifying if your programs are right. Do not blindly copy paste and waste your time.

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

A sample print out is: is is -11 key entered was: w

Page 1 / 3. Page 2 / 18. Page 3 / 8. Page 4 / 21. Page 5 / 15. Page 6 / 20. Page 7 / 15. Total / 100. Pledge:

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Input from Files. Buffered Reader

Selection Statements and operators

Java Flow of Control

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Super-Classes and sub-classes

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

Java Coding 3. Over & over again!

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

Stacks Goodrich, Tamassia

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ June Exam

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

Sorting and Searching

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

CS 113 MIDTERM EXAM 2 SPRING 2013

Full file at

Computer Science 1 Bh

Iterators and File Input

&KDSWHU$UUD\VDQG9HFWRUV

CS1083 Week 2: Arrays, ArrayList

WES-CS GROUP MEETING #9

CSC 273 Data Structures

Selection and Repetition Revisited

Instance Method Development Demo

Input & Output in Java. Standard I/O Exception Handling

i219 Software Design Methodology 8. Dynamic modeling 1 Kazuhiro Ogata (JAIST) Outline of lecture

Polymorphism. return a.doublevalue() + b.doublevalue();

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

Chapter 5 Some useful classes

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CN208 Introduction to Computer Programming

Chapter. Let's explore some other fundamental programming concepts

System.out.print("Enter sales for salesperson " + i + ": "); sales[i] = scan.nextint();

QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Problem Grade Total

First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

CS 101 Exam 2 Spring Id Name

The class Object. Lecture CS1122 Summer 2008

Byte and Character Streams. Reading and Writing Console input and output

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

Question 1a) Trace of program

Searching and Sorting Chapter 18. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp

Selection and Repetition Revisited

Do not open this examination paper until instructed to do so. Section A: answer all the questions. Section B: answer all the questions.

CS111: PROGRAMMING LANGUAGE II

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter --

COS 126 Written Exam 2 (Spring 2015)

/ Download the Khateeb Classes App

Case Study: Savings Account Interest

Chapter 3. Selections

Preview from Notesale.co.uk Page 9 of 108

Recitation: Loop Jul 7, 2008

ANSWER KEY First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

Transcription:

CHAPTER 13 Sorting and Searching The exercises in this chapter are a framework for comparing algorithms empirically. This approach provides students with a means for understanding the finer details of each sorting and search algorithm, and enables them to discover why one sorting or searching algorithm is more appropriate than another. Exercises 13-6 what happens when multiple values occur in the list to be sorted using: a) Selection sort b) Insertion sort Not Provided. 13-1 Trace the steps when sorting the following list: 23, 48, 49, 69, 12, 85, 20, 37, 51, 69, 23 using: a) Selection sort 85 48 49 12 23 20 37 51 69 23 85 69 49 12 23 20 37 51 48 23 85 69 51 12 23 20 37 49 48 23 85 69 51 49 23 20 37 12 48 23 85 69 51 49 48 20 37 12 23 23 85 69 51 49 48 37 20 12 23 23 85 69 51 49 48 37 23 12 20 23 85 69 51 49 48 37 23 23 20 12 85 69 51 49 48 37 23 23 20 12 85 69 51 49 48 37 23 23 20 12 b) Insertion sort 48 23 49 69 12 85 20 37 51 69 23 Java Software Solutions: Foundations of Program Design 408

49 48 23 69 12 85 20 37 51 69 23 69 49 48 23 12 85 20 37 51 69 23 69 49 48 23 12 85 20 37 51 69 23 85 69 49 48 23 12 20 37 51 69 23 85 69 49 48 23 20 12 37 51 69 23 85 69 49 48 37 23 20 12 51 69 23 85 69 51 49 48 37 23 20 12 69 23 85 69 69 51 49 48 37 23 20 12 23 85 69 69 51 49 48 37 23 23 20 12 85 69 69 51 49 48 37 23 23 20 12 13-2 Trace the steps when sorting the following list: 70, 60, 50, 40, 30, 20, 10 using: a) Selection sort 70 60 50 40 30 20 10 70 60 50 40 30 20 10 70 60 50 40 30 20 10 70 60 50 40 30 20 10 70 60 50 40 30 20 10 70 60 50 40 30 20 10 70 60 50 40 30 20 10 b) Insertion sort 70 60 50 40 30 20 10 70 60 50 40 30 20 10 70 60 50 40 30 20 10 Java Software Solutions: Foundations of Program Design 409

70 60 50 40 30 20 10 70 60 50 40 30 20 10 70 60 50 40 30 20 10 70 60 50 40 30 20 10 13-3 Trace the steps when sorting the following list: 11, 22, 33, 44, 55, 66, 77, 88, 99 using: a) Selection sort 99 22 33 44 55 66 77 88 11 99 88 33 44 55 66 77 22 11 99 88 77 44 55 66 33 22 11 99 88 77 66 55 44 33 22 11 99 88 77 66 55 44 33 22 11 99 88 77 66 55 44 33 22 11 99 88 77 66 55 44 33 22 11 99 88 77 66 55 44 33 22 11 99 88 77 66 55 44 33 22 11 b) Insertion sort 22 11 33 44 55 66 77 88 99 33 22 11 44 55 66 77 88 99 44 33 22 11 55 66 77 88 99 55 44 33 22 11 66 77 88 99 66 55 44 33 22 11 77 88 99 77 66 55 44 33 22 11 88 99 88 77 66 55 44 33 22 11 99 99 88 77 66 55 44 33 22 11 Java Software Solutions: Foundations of Program Design 410

99 88 77 66 55 44 33 22 11 13-4 Compare the different executions of each sort with the lists in Problem 13-2 and Problem 13-3. How many comparisons are made in each? Not Provided. 13-5 What optimization can be performed during a linear search if the data is sorted? Once a search processes an element of the data that is greater than the key, the rest of the elements in the sorted data will be greater than the key. Therefore, the search can be terminated without processing all data elements. 13-6 What would happen if the list used in a binary search is not sorted? The algorithm will not work correctly. The execution of the program may not even terminate. An assumption of the binary search is that all data elements to the left of the element being examined are lesser values and all data elements to the right are greater values. If this assumption is not true, then the algorithm (assuming an incorrect ordering) will jump around erratically. 13-7 Why are three assignment statement necessary to exchange two values, as seen in the selection sort? What is the role of the temp variable in the selection sort example? Not Provided. Programming Projects 13-8 Modify the linear search method to optimize the search if you assume the list is sorted. In other words, don t examine any more values than you need to in order to assert that the target value is not present. ******************************************************************* Linear_Search_Test.java In Text Application Authors: Lewis and Loftus Classes: Linear_Search_Test Linear_Search ******************************************************************* ------------------------------------------------------------------- Class Linear_Search_Test contains the driver of a program that searches a list of numbers using a linear search algorithm. Methods: Java Software Solutions: Foundations of Program Design 411

public static void main (String[] args) ------------------------------------------------------------------- public class Linear_Search_Test { =========================================================== Creates an array of integers, then searches for a particular value. =========================================================== public static void main (String[] args) { int numbers[] = {7, -3, 7, 2, 8, -1, 3, 2, 5, 6, 7; System.out.println ("The index of 6 is " + Linear_Search.search (numbers, 6)); method main class Linear_Search_Test ------------------------------------------------------------------- Class Linear_Search contains a static method that searches an array of integers. Methods: public static int search (int[] numbers, int target) ------------------------------------------------------------------- class Linear_Search { =========================================================== Searches the specified array for target using a linear search, but assume the list is sorted in ascending order, and optimize the searching. =========================================================== public static int search (int[] numbers, int target) { int index = 0; Java Software Solutions: Foundations of Program Design 412

while (index < numbers.length) { if (target == numbers[index]) return index; target found else if (target > numbers[index]) return -1; index++; return -1; target not found method search class Linear_Search 13-9 Each of the sorting algorithms presented in this chapter arrange lists of number in ascending order. Rewrite the sort algorithms to arrange a list in descending order. ******************************************************************* Insertion_Sort_Test.java In Text Application Authors: Lewis and Loftus Classes: Insertion_Sort_Test Insertion_Sort ******************************************************************* ------------------------------------------------------------------- Class Insertion_Sort_Test contains the driver of a program that sorts a list of numbers (descending order) using the insertion sort algorithm. Methods: public static void main (String[] args) ------------------------------------------------------------------- public class Insertion_Sort_Test { =========================================================== Java Software Solutions: Foundations of Program Design 413

Creates an array of integers, sorts them, then prints them out. =========================================================== public static void main (String[] args) { int[] numbers = {3, 9, 6, 1, 2; Insertion_Sort.sort (numbers); for (int index = 0; index < numbers.length; index++) System.out.print (numbers[index] + " "); System.out.println (); method main class Insertion_Sort_Test ------------------------------------------------------------------- Class Insertion_Sort contains a static method that sorts an array of integers in descending order. Methods: public static void sort (int[] numbers) ------------------------------------------------------------------- class Insertion_Sort { =========================================================== Sorts the specified array (descending order) using insertion sort. =========================================================== public static void sort (int[] numbers) { for (int index = 1; index < numbers.length; index++) { int key = numbers[index]; int position = index; shift larger values to the left while (position > 0 && numbers[position-1] < key) { numbers[position] = numbers[position-1]; position--; Java Software Solutions: Foundations of Program Design 414

numbers[position] = key; method sort class Insertion_Sort ******************************************************************* Selection_Sort_Test.java In Text Application Authors: Lewis and Loftus Classes: Selection_Sort_Test Selection_Sort ******************************************************************* ------------------------------------------------------------------- Class Selection_Sort_Test contains the driver of a program that sorts a list of numbers (descending order) using the selection sort algorithm. Methods: public static void main (String[] args) ------------------------------------------------------------------- public class Selection_Sort_Test { =========================================================== Creates an array of integers, sorts them, then prints them out. =========================================================== public static void main (String[] args) { int[] numbers = {3, 9, 6, 1, 2; Selection_Sort.sort (numbers); Java Software Solutions: Foundations of Program Design 415

for (int index = 0; index < numbers.length; index++) System.out.print (numbers[index] + " "); System.out.println(); method main class Selection_Sort_Test ------------------------------------------------------------------- Class Selection_Sort contains a static method that sorts an array of integers (descending order). Methods: public static void sort (int[] numbers) ------------------------------------------------------------------- class Selection_Sort { =========================================================== Sorts the specified array (descending order) using selection sort. =========================================================== public static void sort (int[] numbers) { int min, temp; for (int index = 0; index < numbers.length-1; index++) { min = index; for (int scan = index+1; scan < numbers.length; scan++) if (numbers[scan] > numbers[min]) min = scan; swap the values temp = numbers[min]; numbers[min] = numbers[index]; numbers[index] = temp; for (int index1 = 0; index1 < numbers.length; index1++) System.out.print (numbers[index1] + " "); System.out.println(); Java Software Solutions: Foundations of Program Design 416

method sort class Selection_Sort ******************************************************************* Object_Sort_Test.java In Text Application Authors: Lewis and Loftus Classes: Object_Sort_Test Object_Sort Search_Engines Interfaces: Sortable ******************************************************************* import java.net.*; ------------------------------------------------------------------- Class Object_Sort_Test contains the driver of a program that creates a sortable object (a URL list) and sorts it. Methods: public static void main (String[] args) throws MalformedURLException { ------------------------------------------------------------------- public class Object_Sort_Test { =========================================================== Creates a Search_Engines object, then sorts them using the object sort method. =========================================================== public static void main (String[] args) throws MalformedURLException { Search_Engines engines = new Search_Engines(); Object_Sort.sort (engines); Java Software Solutions: Foundations of Program Design 417

for (int index = 0; index < engines.length(); index++) System.out.println (engines.value_at(index)); method main class Object_Sort_Test ------------------------------------------------------------------- Interface Sortable lists the methods needed to sort any list of objects. Methods: boolean compare (Object left, Object right) Object value_at (int position) void set_value (Object value, int position) int length() ------------------------------------------------------------------- interface Sortable { =========================================================== Should be implemented to return true if left > right. =========================================================== boolean compare (Object left, Object right); =========================================================== Should be implemented to return the object at the specified location. =========================================================== Object value_at (int position); =========================================================== Should be implemented to set the value of the specified location. =========================================================== void set_value (Object value, int position); =========================================================== Should be implemented to return the number of items in the list. Java Software Solutions: Foundations of Program Design 418

=========================================================== int length(); interface Sortable ------------------------------------------------------------------- Class Object_Sort contains a static method that sorts any object that implements the Sortable interface. Methods: public static void sort (Sortable items) ------------------------------------------------------------------- class Object_Sort { =========================================================== Sorts the specified items into descending order using an insertion sort that relys on the Sortable methods. =========================================================== public static void sort (Sortable items) { for (int index = 1; index < items.length(); index++) { Object key = items.value_at (index); int position = index; while (position > 0 &&!items.compare (items.value_at (position-1), key)) { items.set_value (items.value_at (position-1), position); position--; items.set_value (key, position); method sort class Object_Sort ------------------------------------------------------------------- Class Search_Engines represents a set of URLs that can be used for web searching. The class implements the Sortable interface Java Software Solutions: Foundations of Program Design 419

so that the list of URLs can be sorted by host name. Constructors: public Search_Engines() throws MalformedURLException Methods: public boolean compare (Object left, Object right) public Object value_at (int index) public void set_value (Object value, int index) public int length() ------------------------------------------------------------------- class Search_Engines implements Sortable { private URL[] sites = new URL[5]; =========================================================== Sets up the list of search engines. =========================================================== public Search_Engines() throws MalformedURLException { sites[0] = new URL ("http:www.lycos.com"); sites[1] = new URL ("http:www.yahoo.com"); sites[2] = new URL ("http:www.webcrawler.com"); sites[3] = new URL ("http:www.excite.com"); sites[4] = new URL ("http:www.infoseek.com"); constructor Search_Engines =========================================================== Returns true if the host of left is alphabetically after the host of right. =========================================================== public boolean compare (Object left, Object right) { URL site1 = (URL) left; URL site2 = (URL) right; String host1 = site1.gethost(); String host2 = site2.gethost(); Java Software Solutions: Foundations of Program Design 420

if (host1.compareto(host2) > 0) return true; else return false; method compare =========================================================== Returns the URL object at the specified index. =========================================================== public Object value_at (int index) { return (sites[index]); method value_at =========================================================== Sets the URL object at the specified index. =========================================================== public void set_value (Object value, int index) { sites[index] = (URL)value; method set_value =========================================================== Returns the number of URLs stored in the object. =========================================================== public int length() { return (sites.length); method length class Search_Engines 13-10 Design and implement a program which reads every word of a paragraph of text and counts the occurrences of each word. Use hashing as part of the solution. ******************************************************************* Paragraph_HashTest.java In Text Applet Authors: Lewis and Loftus Classes: Paragraph_Hash_Test Paragraph_Hash Word_Object Java Software Solutions: Foundations of Program Design 421

******************************************************************* import java.io.*; import java.util.*; ------------------------------------------------------------------- Class Paragraph_Hash_Test contains the driver of a program that obtains a paragraph of text, places in a hash table and prints the frequency of the words contained in the paragraph. Methods: public static void main (String[] args) ------------------------------------------------------------------- public class Paragraph_Hash_Test { public static void main (String [] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); Get the paragraph from the user and send it to the hasher System.out.println("Enter a paragraph of text: "); Paragraph_Hash.hasher (stdin.readline()); method main class Paragraph_Hash_Test ------------------------------------------------------------------- Class Paragraph_Hash contains the hashing routine which accepts a String of text, places each unique word found in a Word_Object and inserts it into the hash table. Repeated words have their frequency counters incremented. When all words from the paragraph have been handled, a summary of word frequencies is printed. Methods: public static void hasher (String inputstring) ------------------------------------------------------------------- Java Software Solutions: Foundations of Program Design 422

class Paragraph_Hash { public static void hasher(string inputstring) throws NoSuchElementException { Create a hash table to store the words Hashtable table = new Hashtable(10); Create a string tokenizer to parse the paragraph words StringTokenizer tokenizer = new StringTokenizer(inputString); while(tokenizer.hasmoretokens()) { Get the next word from the paragraph String element = tokenizer.nexttoken(); Check to see if this word is in the hash table already if (!table.containskey(element)) table.put(element, new Word_Object (element)); else ((Word_Object) table.get(element)).incrementcount(); while loop Get the enumeration of the hash table for printing Enumeration enum = table.elements(); while (enum.hasmoreelements()) System.out.println(enum.nextElement().toString()); method main class Paragraph_Hash ------------------------------------------------------------------- Class Word_Object represents the data type inserted into the hash table. It will maintain the text of the hashed word and the current frequency of the word. Methods are provided for the printing of the object, incrementing the frequency counter. Methods: public Word_Object (String str) public void incrementcount () public String tostring() Java Software Solutions: Foundations of Program Design 423

------------------------------------------------------------------- class Word_Object { private String word; private int count; public Word_Object (String str) { word = str; count = 1; constructor Word_Object public void incrementcount () { count++; method incrementcount public String tostring () { return ("Word = " + word + " method tostring frequency = " + count); class Word_Object 13-11 Design and implement a program which sorts a list of People objects, each of which contains a name, age, and salary. Allow the list to be sorted by any of these values, depending on the sort method invoked. ******************************************************************* People_Sort_Test.java In Text Application Authors: Lewis and Loftus Classes: People_Sort_Test People People_Sort ******************************************************************* ------------------------------------------------------------------- Class People_Sort_Test contains the driver of a program that sorts a list of people using the insertion sort algorithm. Methods: Java Software Solutions: Foundations of Program Design 424

public static void main (String[] args) ------------------------------------------------------------------- public class People_Sort_Test { =========================================================== Creates an array of People, sorts them, then prints them out. =========================================================== public static void main (String[] args) { People[] my_friends = { new People ("Pete DePasquale", 29, 31000), new People ("Sam Perugini", 20, 15000), new People ("Thomas Standish", 35, 45000), new People ("Grady Booch", 19, 30000), new People ("Fred Brooks", 45, 750000) ; System.out.println("\n\nPeople sorted by names:"); System.out.println("==============================="); People_Sort.sort_By_Name (my_friends); for (int index = 0; index < my_friends.length; index++) System.out.println (my_friends[index].tostring()); System.out.println("\n\nPeople sorted by age:"); System.out.println("==============================="); People_Sort.sort_By_Age (my_friends); for (int index = 0; index < my_friends.length; index++) System.out.println (my_friends[index].tostring()); System.out.println("\n\nPeople sorted by salary:"); System.out.println("==============================="); People_Sort.sort_By_Salary (my_friends); for (int index = 0; index < my_friends.length; index++) System.out.println (my_friends[index].tostring()); method main Java Software Solutions: Foundations of Program Design 425

class People_Sort_Test ------------------------------------------------------------------- Class People contains a person's name, age and salary information. Access methods to obtain the name, age and salary are provided as well as a tostring method to print the contents all on one line. Methods: public People(String nm, int ag, int sal) public String tostring() public String getname() public int getage() public int getsalary() ------------------------------------------------------------------- class People { private String name; private int age; private int salary; public People(String nm, int ag, int sal) { name = nm; age = ag; salary = sal; People constructor public String tostring() { return (name + " " + age + " $" + salary); method tostring public String getname() { return name; method getname Java Software Solutions: Foundations of Program Design 426

public int getage() { return age; method getage public int getsalary() { return salary; method getsalary class People ------------------------------------------------------------------- Class People_Sort contains a static method that sorts an array of People. Methods: public static void sort_by_name (People[] friends) public static void sort_by_age (People[] friends) public static void sort_by_salary (People[] friends) ------------------------------------------------------------------- class People_Sort { =========================================================== Sorts the specified array (by person's name) using insertion sort. =========================================================== public static void sort_by_name (People[] friends) { for (int index = 1; index < friends.length; index++) { People key = friends[index]; int position = index; shift larger values to the right while (position > 0 && friends[position-1].getname(). compareto(key.getname()) > 0) { friends[position] = friends[position-1]; position--; Java Software Solutions: Foundations of Program Design 427

friends[position] = key; method sort_by_name =========================================================== Sorts the specified array (by person's age) using insertion sort. =========================================================== public static void sort_by_age (People[] friends) { for (int index = 1; index < friends.length; index++) { People key = friends[index]; int position = index; shift larger values to the right while (position > 0 && friends[position-1].getage() > key.getage()) { friends[position] = friends[position-1]; position--; friends[position] = key; method sort_by_age =========================================================== Sorts the specified array (by person's salary) using insertion sort. =========================================================== public static void sort_by_salary (People[] friends) { for (int index = 1; index < friends.length; index++) { People key = friends[index]; int position = index; shift larger values to the right while (position > 0 && friends[position-1].getsalary() > key.getsalary()) { Java Software Solutions: Foundations of Program Design 428

friends[position] = friends[position-1]; position--; friends[position] = key; method sort_by_salary class People_Sort 13-12 Design and implement a generic binary search algorithm. Exercise the class by storing a list of employees, and searching for individuals by name. ******************************************************************* Employee_Search_Test.java In Text Application Authors: Lewis and Loftus Classes: Employee_Search_Test Employee Object_Binary_Search ******************************************************************* import java.io.*; ------------------------------------------------------------------- Class Employee_Sort_Test contains the driver of a program that searches a list of employees for a particular employee and prints that person's information. Methods: public static void main (String[] args) ------------------------------------------------------------------- public class Employee_Search_Test { Java Software Solutions: Foundations of Program Design 429

=========================================================== Creates an array of Employees, and then searches for a specific individual. =========================================================== public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); Employee[] subordinates = { new Employee ("Fred Brooks", 45, 750000), new Employee ("Grady Booch", 19, 30000), new Employee ("Pete DePasquale", 29, 31000), new Employee ("Sam Perugini", 20, 15000), new Employee ("Thomas Standish", 35, 45000) ; System.out.print ("Enter the name of the person to seach for: "); int result = Object_Binary_Search.search(subordinates, stdin.read- Line()); if (result == -1) System.out.println("\nSearch failed."); else System.out.println("\n" + subordinates[result].tostring()); method main class Employee_Search_Test ------------------------------------------------------------------- Interface Searchable lists the method needed to compare any list of objects during a search operation Methods: boolean compare (Object left, Object right) ------------------------------------------------------------------- interface Searchable { Java Software Solutions: Foundations of Program Design 430

=========================================================== Should be implemented to return 0 if this = target, 1 if this > target and -1 if this < target =========================================================== int compare (Object target); interface Searchable ------------------------------------------------------------------- Class Employee contains a person's name, age and salary information. Access methods to obtain the name, age and salary are provided as well as a tostring method to print the contents all on one line and a comparison method. Methods: public Employee (String nm, int ag, int sal) public String tostring () public String getname () public int getage () public int getsalary () public boolean compare (Object obj) ------------------------------------------------------------------- class Employee implements Searchable { private String name; private int age; private int salary; public Employee(String nm, int ag, int sal) { name = nm; age = ag; salary = sal; People constructor =========================================================== Returns the string representation of this object =========================================================== Java Software Solutions: Foundations of Program Design 431

public String tostring () { return (name + " " + age + " $" + salary); method tostring =========================================================== Returns the name of the employee =========================================================== public String getname () { return name; method getname =========================================================== Returns the age of the employee =========================================================== public int getage () { return age; method getage =========================================================== Returns the salary of the employee =========================================================== public int getsalary () { return salary; method getsalary =========================================================== Returns 0 if this = target, 1 if this > target and -1 if this < target =========================================================== public int compare (Object obj) { int comparison_result; if (obj instanceof String) comparison_result = name.compareto((string) obj); else comparison_result = 0; if (comparison_result > 0) return 1; else Java Software Solutions: Foundations of Program Design 432

return -1; method compare =========================================================== Returns true if this Employee's name is equal to target =========================================================== public boolean equals(object target) { if (this.name.equals((string) target)) return true; else return false; class Employee ------------------------------------------------------------------- Class Object_Binary_Search contains a static method that searches an array of Objects. Methods: public static int search (Object[] numbers, Object target) ------------------------------------------------------------------- class Object_Binary_Search { =========================================================== Searches the specified array for target using a binary search. =========================================================== public static int search (Searchable[] items, Object target) { int index; int left = 0, right = items.length - 1; while (left <= right) { index = (left + right) / 2; if (items[index].equals(target)) return index; target found Java Software Solutions: Foundations of Program Design 433

if (items[index].compare(target) < 0) left = index + 1; else right = index - 1; return -1; target not found method search class Object_Binary_Search 13-13 Modify the algorithms for the selection sort and the insertion sort to count the: Number of comparisons Number of exchanges Number of times each loop is executed ******************************************************************* Insertion_Sort_Test2.java In Text Application Authors: Lewis and Loftus Classes: Insertion_Sort_Test Insertion_Sort ******************************************************************* ------------------------------------------------------------------- Class Insertion_Sort_Test2 contains the driver of a program that sorts a list of numbers using the insertion sort algorithm. Methods: public static void main (String[] args) ------------------------------------------------------------------- public class Insertion_Sort_Test2 { Java Software Solutions: Foundations of Program Design 434

=========================================================== Creates an array of integers, sorts them, then prints them out. =========================================================== public static void main (String[] args) { int[] numbers = new int[4000]; for (int index = 0; index < numbers.length; index++) { numbers[index] = (int)(math.random()*100000); Insertion_Sort2.sort (numbers); for (int index = 0; index < numbers.length; index++) System.out.println (numbers[index]); Insertion_Sort2.printSummary(); method main class Insertion_Sort_Test ------------------------------------------------------------------- Class Insertion_Sort contains a static method that sorts an array of integers. Methods: public static void sort (int[] numbers) public static void printsummary () ------------------------------------------------------------------- class Insertion_Sort2 { public static int numberofcomparisons; public static int numberofexchanges; public static int numberofloopexecutions; =========================================================== Sorts the specified array using insertion sort. =========================================================== Java Software Solutions: Foundations of Program Design 435

public static void sort (int[] numbers) { numberofcomparisons = numberofexchanges = numberofloopexecutions = 0; for (int index = 1; index < numbers.length; index++) { int key = numbers[index]; int position = index; shift larger values to the right while (position > 0 && numbers[position-1] > key) { numbers[position] = numbers[position-1]; position--; numberofcomparisons++; numberofexchanges++; numberofloopexecutions++; numbers[position] = key; numberofexchanges++; method sort =========================================================== Prints the statistics of the sort. =========================================================== public static void printsummary () { System.out.println("The total number of comparisons was: " + numberofcomparisons); System.out.println("The total number of exchanges was: " + numberofexchanges); System.out.println("The total number of loop executions was: " + numberofloopexecutions); method printsummary class Insertion_Sort ******************************************************************* Selection_Sort_Test2.java In Text Application Java Software Solutions: Foundations of Program Design 436

Authors: Lewis and Loftus Classes: Selection_Sort_Test Selection_Sort ******************************************************************* ------------------------------------------------------------------- Class Selection_Sort_Test2 contains the driver of a program that sorts a list of numbers using the selection sort algorithm. Methods: public static void main (String[] args) ------------------------------------------------------------------- public class Selection_Sort_Test2 { =========================================================== Creates an array of integers, sorts them, then prints them out. =========================================================== public static void main (String[] args) { int[] numbers = new int[4000]; for (int index = 0; index < numbers.length; index++) { numbers[index] = (int)(math.random()*100); long start = System.currentTimeMillis(); Selection_Sort2.sort (numbers); long stop = System.currentTimeMillis(); System.out.println ("Time is " + (stop - start)); for (int index = 0; index < numbers.length; index++) System.out.println (numbers[index]); Selection_Sort2.printSummary(); method main Java Software Solutions: Foundations of Program Design 437

class Selection_Sort_Test2 ------------------------------------------------------------------- Class Selection_Sort contains a static method that sorts an array of integers. Methods: public static void sort (int[] numbers) public static void printsummary () ------------------------------------------------------------------- class Selection_Sort2 { public static int numberofcomparisons; public static int numberofexchanges; public static int numberofloopexecutions; =========================================================== Sorts the specified array using selection sort. =========================================================== public static void sort (int[] numbers) { int min, temp; numberofcomparisons = numberofexchanges = numberofloopexecutions = 0; for (int index = 0; index < numbers.length-1; index++) { numberofloopexecutions++; min = index; for (int scan = index+1; scan < numbers.length; scan++) { numberofcomparisons++; if (numbers[scan] < numbers[min]) { min = scan; swap the values temp = numbers[min]; numbers[min] = numbers[index]; Java Software Solutions: Foundations of Program Design 438

numbers[index] = temp; numberofexchanges++; method sort =========================================================== Prints the statistics of the sort. =========================================================== public static void printsummary () { System.out.println("The total number of comparisons was: " + numberofcomparisons); System.out.println("The total number of exchanges was: " + numberofexchanges); System.out.println("The total number of loop executions was: " + numberofloopexecutions); method printsummary class Selection_Sort Java Software Solutions: Foundations of Program Design 439