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

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

Embed Size (px)

Citation preview

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

1

Chapter 15: Algorithms1

Chapter 15Algorithms

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

2

Chapter 15: Algorithms2

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); }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

3

Chapter 15: Algorithms3

Class SelSort.java

public class SelSort /** Finds the smallest element in an array range.

@param a the array to search @param from the first position in a to compare @return the position of the smallest element in the range a[from]...a[a.length - 1]*/

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

4

Chapter 15: Algorithms4

{ 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 array. @param 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); } }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

5

Chapter 15: Algorithms5

Class ArrayUtil.java

import java.util.Random;

/** This class contains utility methods for array manipulation.*/

public class ArrayUtil{ /** Creates an array filled with random values. @param length the length of the array @param n the number of possible random values @return 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++)

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

6

Chapter 15: Algorithms6

a[i] = generator.nextInt(n); return a; }

/** Swaps two elements in an array. @param a the array with the elements to swap @param i the index of one of the elements @param 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; }

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

7

Chapter 15: Algorithms7

/** Prints all elements in an array. @param 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(); }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

8

Chapter 15: Algorithms8

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(); }

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

9

Chapter 15: Algorithms9

/** 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;}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

10

Chapter 15: Algorithms10

/** Returns the total elapsed time. @return the total elapsed time*/public long getElapsedTime(){ if (isRunning) { long endTime = System.currentTimeMillis();

elapsedTime = elapsedTime + endTime - startTime; startTime = endTime;}return elapsedTime;}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

11

Chapter 15: Algorithms11

/** 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;}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

12

Chapter 15: Algorithms12

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);

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

13

Chapter 15: Algorithms13

// 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"); }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

14

Chapter 15: Algorithms14

Figure 1Time Taken Selection bySort

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

15

Chapter 15: Algorithms15

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); }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

16

Chapter 15: Algorithms16

Class MergeSort.java

public class MergeSort{ /** Merges two adjacent subranges of an array @param a the array with entries to be merged @param from the index of the first element of the first range @param mid the index of the last element of the first range @param 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];

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

17

Chapter 15: Algorithms17

int i1 = from; // next element to consider in the first rangeint i2 = mid + 1; // next element to consider in the second rangeint j = 0; // next open position in b

// as long as neither i1 nor i2 past the end, move// the smaller element into bwhile (i1 <= mid && i2 <= to){ if (a[i1] < a[i2]) { b[j] = a[i1]; i1++; } else { b[j] = a[i2]; i2++; }

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

18

Chapter 15: Algorithms18

j++;}// note that only one of the two while loops// below is executed

// copy any remaining entries of the first halfwhile (i1 <= mid){ b[j] = a[i1]; i1++; j++;}

// copy any remaining entries of the second halfwhile (i2 <= to){ b[j] = a[i2]; i2++; j++;}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

19

Chapter 15: Algorithms19

/** Sorts a range of an array, using the merge sort algorithm. @param a the array to sort @param from the first index of the range to sort @param 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];}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

20

Chapter 15: Algorithms20

/** Sorts an array, using the merge sort algorithm. @param a the array to sort */ public static void sort(int[] a) { mergeSort(a, 0, a.length - 1); }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

21

Chapter 15: Algorithms21

Figure 2Merge Sort Timing(Rectangles) versus SelectionSort (Circles)

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

22

Chapter 15: Algorithms22

Figure 3Babbage’s Difference Engine

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

23

Chapter 15: Algorithms23

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); }

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

24

Chapter 15: Algorithms24

/** Finds a value in an array, using the linear search algorithm. @param a the array @param v the value to search @return 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++)

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

25

Chapter 15: Algorithms25

{ if (a[i] == v) return i; } return -1; }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

26

Chapter 15: Algorithms26

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); }

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

27

Chapter 15: Algorithms27

/** Finds a value in a range of a sorted array, using the binary search algorithm. @param a the sorted array @param from the first index in the range to search @param to the last index in the range to search @param v the value to search @return 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;

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

28

Chapter 15: Algorithms28

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);}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

29

Chapter 15: Algorithms29

/** Finds a value in a sorted array, using the binary search algorithm. @param a the sorted array @param v the value to search @return 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); }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

30

Chapter 15: Algorithms30

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");}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

31

Chapter 15: Algorithms31

/** Computes a Fibonacci number. @param n an integer @return the nth Fibonacci number */ public static int fib(int n) { if (n <= 2) return 1; else return fib(n - 1) + fib(n - 2); }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

32

Chapter 15: Algorithms32

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); }

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

33

Chapter 15: Algorithms33

/** Computes a Fibonacci number. @param n an integer @return the nth 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; }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

34

Chapter 15: Algorithms34

Program FibLoop.java

public class FibLoop{ public static void main(String[] args) { ConsoleReader console = new ConsoleReader(System.in); System.out.println("Enter n: ");

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

35

Chapter 15: Algorithms35

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");}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

36

Chapter 15: Algorithms36

/** Computes a Fibonacci number. @param n an integer @return the nth 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; }}

©2000, John Wiley & Sons, Inc.Horstmann/Java Essentials, 2/e

37

Chapter 15: Algorithms37

Figure 4Graphical Animation