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