Chapter 15: Algorithms 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 15 Algorithms.

Slides:



Advertisements
Similar presentations
Sorting Sorting places data in ascending or descending order, based on one or more sort keys E.g. A list of names could be sorted alphabetically, bank.
Advertisements

©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
Sorting Algorithms: Merge and Quick. Lecture Objectives Learn how to implement the simple advanced sorting algorithms (merge and quick) Learn how to implement.
1 Lecture 23 Searching Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
1 Lecture 21 Introduction to Sorting I Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.  Brief.
Problem Solving #6: Search & Sort ICS Outline Review of Key Topics Review of Key Topics Problem 1: Recursive Binary Search … Problem 1: Recursive.
Programming with Recursion. Example of Recursion (Ask Until the User Gets It Right) import java.util.* ; public class CountDown { private int count; public.
CHAPTER 17 RECURSION CHAPTER GOALS –To learn about the method of recursion –To understand the relationship between recursion and iteration –To analysis.
Sorting Algorithms: Selection, Insertion and Bubble.
Complexity Analysis (Part III ) Analysis of Some Sorting Algorithms. Analysis of Recursive Algorithms.
1 Searching Algorithms Overview  What is Searching?  Linear Search and its Implementation.  Brief Analysis of Linear Search.  Binary Search and its.
1 Search & Sorting Using Java API Searching and Sorting Using Standard Classes  Searching data other than primitive type.  Comparable interface.  Implementing.
1 Sorting Algorithms (Part I) Sorting Algoritms (Part I) Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 14 – Sorting and Searching.
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Fourteen: Sorting and Searching.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 13 – Sorting and Searching.
Recursion A recursive computation solves a problem by using the solution of the same problem with simpler values The same computation occurs repeatedly.
Building Java Programs Chapter 13 Searching reading: 13.3.
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.
Copyright © 2013 by John Wiley & Sons. All rights reserved. SORTING AND SEARCHING CHAPTER Slides by Rick Giles 14.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 14 – Sorting and Searching.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Sorting and Searching.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 14 – Sorting and Searching.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 8: Testing and Debugging 1 Chapter 8 Testing and Debugging.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 14 – Sorting and Searching.
Searching. The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing.
CHAPTER 18 SORTING AND SEARCHING. CHAPTER GOALS To study the several searching and sorting algorithms To appreciate that algorithms for the same task.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 11: Arrays and Vectors 1 Chapter 11 Arrays and Vectors.
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
SortingBigOh Sorting and "Big Oh" Adapted for ASFA from a presentation by: Barb Ericson Georgia Tech Aug 2007 ASFA AP Computer Science.
Comparison-Based Sorting & Analysis Smt Genap
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
CS 46B: Introduction to Data Structures July 2 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 14 Sorting and Searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Sorting  Sorting places data in ascending or descending order, based on one or more sort.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
CSE 143 Lecture 16 Sorting reading: 13.1, slides created by Marty Stepp
Merge Sort. In plain English: if the size of the array > 1, split the array into two halves, and recursively sort both halves; when the sorts return,
CS 162 Intro to Programming II Sorting Introduction & Selection Sort 1.
Building Java Programs Chapter 13 Searching and Sorting Copyright (c) Pearson All rights reserved.
Building Java Programs Chapter 13 Sorting reading: 13.3, 13.4.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
Fibonacci Sequence Fibonacci sequence is a sequence of numbers defined by f 1 = 1 f 2 = 1 f n = f n-1 + f n-2 First ten terms – 1, 1, 2, 3, 5, 8, 13, 21,
Lecture 25: Searching and Sorting
Using recursion for Searching and Sorting
Fundamentals of Algorithms MCS - 2 Lecture # 11
Lecture 14 Searching and Sorting Richard Gesick.
Ch 14: Search and Sorting Yonglei Tao.
Building Java Programs
Chapter 19 Sorting and Searching
Lecture 11 Searching and Sorting Richard Gesick.
CSE 154 Sorting reading: 13.3, 13.4
Adapted from slides by Marty Stepp and Stuart Reges
slides created by Marty Stepp
CSE 143 Sorting reading: 13.3, 13.4.
Chapter 14 – Sorting and Searching
CSE 373 Data Structures and Algorithms
Module 8 – Searching & Sorting Algorithms
slides adapted from Marty Stepp
Application: Efficiency of Algorithms II
Application: Efficiency of Algorithms II
Module 8 – Searching & Sorting Algorithms
Stacks, Queues, ListNodes
Sorting Algorithms.
Presentation transcript:

Chapter 15: Algorithms 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 15 Algorithms

Chapter 15: Algorithms 2 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 2 Program SelSortTest.java public class SelSortTest { public static void main(String[] args) { int[] a = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); SelSort.sort(a); ArrayUtil.print(a); }

Chapter 15: Algorithms 3 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 3 Class SelSort.java public class SelSort /** Finds the smallest element in an array a the array to from the first position in a to the position of the smallest element in the range a[from]...a[a.length - 1] */

Chapter 15: Algorithms 4 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 4 { public static int minimumPosition(int[] a, int from) { int minPos = from; for (int i = from + 1; i < a.length; i++) if (a[i] < a[minPos]) minPos = i; return minPos; } /** Sorts an a the array to sort */ public static void sort(int[] a) { for (int n = 0; n < a.length - 1; n++) { int minPos = minimumPosition(a, n); if (minPos != n) ArrayUtil.swap(a, minPos, n); }

Chapter 15: Algorithms 5 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 5 Class ArrayUtil.java import java.util.Random; /** This class contains utility methods for array manipulation. */ public class ArrayUtil { /** Creates an array filled with random length the length of the n the number of possible random an array filled with length numbers between 0 and n-1 */ public static int[] randomIntArray(int length, int n) { int[] a = new int[length]; Random generator = new Random(); for (int i = 0; i < a.length; i++)

Chapter 15: Algorithms 6 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 6 a[i] = generator.nextInt(n); return a; } /** Swaps two elements in an a the array with the elements to i the index of one of the j the index of the other element */ public static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; }

Chapter 15: Algorithms 7 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 7 /** Prints all elements in an a the array to print */ public static void print(int[] a) { for (int i = 0; i < a.length; i++) System.out.print(a[i] + ” "); System.out.println(); }

Chapter 15: Algorithms 8 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 8 Class StopWatch.java /** A stopwatch accumulates time when it is running. You can repeatedly start and stop the stopwatch. You can use a stopwatch to measure the running time of a program. */ public class StopWatch { /** Constructs a stopwatch that is in the stopped state and has no time accumulated. */ public StopWatch() { reset(); }

Chapter 15: Algorithms 9 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 9 /** Starts the stopwatch. Time starts accumulating now. */ public void start() { if (isRunning) return; isRunning = true; startTime = System.currentTimeMillis(); } /** Stops the stopwatch. Time stops accumulating and is added to the elapsed time. */ public void stop() { if (!isRunning) return; isRunning = false; long endTime = System.currentTimeMillis(); elapsedTime = elapsedTime + endTime - startTime; }

Chapter 15: Algorithms 10 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 10 /** Returns the total elapsed the total elapsed time */ public long getElapsedTime() { if (isRunning) { long endTime = System.currentTimeMillis(); elapsedTime = elapsedTime + endTime - startTime; startTime = endTime; } return elapsedTime; }

Chapter 15: Algorithms 11 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 11 /** Stops the watch and resets the elapsed time to 0. */ public void reset() { isRunning = false; elapsedTime = 0; } private long elapsedTime; private long startTime; private boolean isRunning; }

Chapter 15: Algorithms 12 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 12 Program SelSortTime.java public class SelSortTime { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); // construct random array System.out.println("Enter array size: "); int n = console.readInt(); int[] a = ArrayUtil.randomIntArray(n, 100);

Chapter 15: Algorithms 13 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 13 // use stopwatch to time selection sort StopWatch timer = new StopWatch(); timer.start(); SelSort.sort(a); timer.stop(); System.out.println("Elapsed time: " + timer.getElapsedTime() + ” milliseconds"); }

Chapter 15: Algorithms 14 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 14 Figure 1 Time Taken Selection by Sort

Chapter 15: Algorithms 15 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 15 Program MergeSortTest.java public class MergeSortTest { public static void main(String[] args) { int[] a = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); MergeSort.sort(a); ArrayUtil.print(a); }

Chapter 15: Algorithms 16 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 16 Class MergeSort.java public class MergeSort { /** Merges two adjacent subranges of an a the array with entries to be from the index of the first element of the first mid the index of the last element of the first to the index of the last element of the second range */ public static void merge(int[] a, int from, int mid, int to) { int n = to - from + 1; // size of the range to be merged // merge both halves into a temporary array b int[] b = new int[n];

Chapter 15: Algorithms 17 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 17 int i1 = from; // next element to consider in the first range int i2 = mid + 1; // next element to consider in the second range int j = 0; // next open position in b // as long as neither i1 nor i2 past the end, move // the smaller element into b while (i1 <= mid && i2 <= to) { if (a[i1] < a[i2]) { b[j] = a[i1]; i1++; } else { b[j] = a[i2]; i2++; }

Chapter 15: Algorithms 18 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 18 j++; } // note that only one of the two while loops // below is executed // copy any remaining entries of the first half while (i1 <= mid) { b[j] = a[i1]; i1++; j++; } // copy any remaining entries of the second half while (i2 <= to) { b[j] = a[i2]; i2++; j++; }

Chapter 15: Algorithms 19 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 19 /** Sorts a range of an array, using the merge sort a the array to from the first index of the range to to the last index of the range to sort */ public static void MergeSort(int[] a, int from, int to) { if (from == to) return; int mid = (from + to) / 2; // sort the first and the second half mergeSort(a, from, mid); mergeSort(a, mid + 1, to); merge(a, from, mid, to); } // copy back from the temporary array for (j = 0; j < n; j++) a[from + j] = b[j]; }

Chapter 15: Algorithms 20 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 20 /** Sorts an array, using the merge sort a the array to sort */ public static void sort(int[] a) { mergeSort(a, 0, a.length - 1); }

Chapter 15: Algorithms 21 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 21 Figure 2 Merge Sort Timing (Rectangles) versus Selection Sort (Circles)

Chapter 15: Algorithms 22 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 22 Figure 3 Babbag e ’s Difference Engine

Chapter 15: Algorithms 23 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 23 Program LinearSearch.java public class LinearSearch { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); // construct random array int[] a = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); System.out.println("Enter number to search for:"); int n = console.readInt(); int j = search(a, n); System.out.println("Found in position ” + j); }

Chapter 15: Algorithms 24 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 24 /** Finds a value in an array, using the linear search a the v the value to the index at which the value occurs, or -1 if it does not occur in the array */ public static int search(int[] a, int v) { for (int i = 0; i < a.length; i++)

Chapter 15: Algorithms 25 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 25 { if (a[i] == v) return i; } return -1; }

Chapter 15: Algorithms 26 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 26 Program BinarySearch.java public class BinarySearch { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); // construct random array and sort it int[] v = ArrayUtil.randomIntArray(20, 100); SelSort.sort(v); ArrayUtil.print(v); System.out.println("Enter number to search for:"); int n = console.readInt(); int j = search(v, n); System.out.println("Found in position ” + j); }

Chapter 15: Algorithms 27 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 27 /** Finds a value in a range of a sorted array, using the binary search a the sorted from the first index in the range to to the last index in the range to v the value to the index at which the value occurs, or -1 if it does not occur in the array */ public static int binarySearch(int[] a, int from, int to, int v) { if (from > to) return -1;

Chapter 15: Algorithms 28 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 28 int mid = (from + to) / 2; int diff = a[mid] - v; if (diff == 0) // a[mid] == v return mid; else if (diff < 0) // a[mid] < v return binarySearch(a, mid + 1, to, v); else return binarySearch(a, from, mid - 1, v); }

Chapter 15: Algorithms 29 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 29 /** Finds a value in a sorted array, using the binary search a the sorted v the value to the index at which the value occurs, or -1 if it does not occur in the array */ public static int search(int[] a, int v) { return binarySearch(a, 0, a.length -1, v); }

Chapter 15: Algorithms 30 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 30 Program FibTime.java public class FibTime { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Enter n: "); int n = console.readInt(); // use stopwatch to time Fibonacci number computation StopWatch timer = new StopWatch(); timer.start(); int f = fib(n); timer.stop(); System.out.println("fib(“ + n + ")= ” + f); System.out.println("Elapsed time = " + timer.getElapsedTime() + “ milliseconds"); }

Chapter 15: Algorithms 31 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 31 /** Computes a Fibonacci n an the n th Fibonacci number */ public static int fib(int n) { if (n <= 2) return 1; else return fib(n - 1) + fib(n - 2); }

Chapter 15: Algorithms 32 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 32 Program FibTrace.java public class FibTrace { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Enter n:"); int n = console.readInt(); int f = fib(n); System.out.println("fib(” + n + ") = ” + f); }

Chapter 15: Algorithms 33 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 33 /** Computes a Fibonacci n an the n th Fibonacci number */ public static int fib(int n) { System.out.println("Entering fib: n = ” + n); int f; if (n <= 2) f = 1; else f = fib(n - 1) + fib(n - 2); System.out.println("Exiting fib: n = ” + n + ” return value = ” + f); return f; }

Chapter 15: Algorithms 34 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 34 Program FibLoop.java public class FibLoop { public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Enter n: ");

Chapter 15: Algorithms 35 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 35 int n = console.readInt(); // use stopwatch to time Fibonacci number computation StopWatch timer = new StopWatch(); timer.start(); int f = fib(n); timer.stop(); System.out.println("fib(” + n + ") = ” + f); System.out.println("Elapsed time = " + timer.getElapsedTime() + ” milliseconds"); }

Chapter 15: Algorithms 36 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 36 /** Computes a Fibonacci n an the n th Fibonacci number */ public static int fib(int n) { if (n <= 2) return 1; int fold = 1; int fold2 = 1; int fnew = 1; for (int i = 3; i <= n; i++) { fnew = fold + fold2; fold2 = fold; fold = fnew; } return fnew; }

Chapter 15: Algorithms 37 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 37 Figure 4 Graphical Animation