Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Fibonacci Sequence • Fibonacci sequence is a sequence of numbers defined by f1 = 1 f2 = 1 fn = fn-1 + fn-2 • First ten terms – 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: import java.util.Scanner; /** This program computes Fibonacci numbers using a recursive method. */ public class FibTester { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter n: "); int n = in.nextInt(); for (int i = 1; i <= n; i++) { long f = fib(i); System.out.println("fib(" + i + ") = " + f); } } /** Computes a Fibonacci number. @param n an integer @return the nth Fibonacci number */ public static long fib(int n) { if (n <= 2) return 1; else return fib(n - 1) + fib(n - 2); } } A tester program used to generate and print Fibonacci numbers Note that the method fib(int n) calls itself recursively Recursion • A recursive computation solves a problem by using the solution of the same problem with simpler values • For recursion to terminate, there must be special cases for the simplest inputs. – To complete our example, we must handle n <= 2 • If (n <= 2) return 1; • Two key requirements for recursion success: – Every recursive call must simplify the computation in some way – There must be special cases to handle the simplest computations directly Sorting and Searching • Goals – To study several sorting and searching algorithms – To appreciate that algorithms for the same task can differ widely in performance – To understand the big-Oh notation – To learn how to estimate and compare the performance of algorithms – To learn how to measure the running time of a program // Sort an array's values into ascending order. import java.awt.*; import javax.swing.*; public class BubbleSort extends JFrame { public BubbleSort() { JTextArea outputArea = new JTextArea(); Container container = getContentPane(); container.add( outputArea ); int array[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; String output = "Data items in original order\n"; // append original array values to String output for ( int counter = 0; counter < array.length; counter++ ) output += " " + array[ counter ]; bubbleSort( array ); // sort array output += "\n\nData items in ascending order\n"; // append sorted\ array values to String output for ( int counter = 0; counter < array.length; counter++ ) output += " " + array[ counter ]; outputArea.setText( output ); setSize( 375, 200 ); setVisible( true ); } Bubble Sort // sort elements of array with bubble sort public void bubbleSort( int array2[] ) { // loop to control number of passes for ( int pass = 1; pass < array2.length; pass++ ) { // loop to control number of comparisons for ( int element = 0; element < array2.length - 1; element++ ) { // compare side-by-side elements and swap them if // first element is greater than second element if ( array2[ element ] > array2[ element + 1 ] ) swap( array2, element, element + 1 ); } } } // swap two elements of an array public void swap( int array3[], int first, int second ) int hold; // temporary holding area for swap hold = array3[ first ]; array3[ first ] = array3[ second ]; array3[ second ] = hold; } } { public static void main( String args[] ) { BubbleSort application = new BubbleSort (); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } // end class BubbleSort Bubble Sort public class InsertionSorter{ public InsertionSorter(int[] anArray) { a = anArray; } public void sort() { for (int i = 1; i < a.length; i++) { int next = a[i]; // Move all larger elements up int j = i; while (j > 0 && a[j - 1] > next) { a[j] = a[j - 1]; j--; } // Insert the element a[j] = next; } } private int[] a; } Insertion Sort public class SelectionSortTester { public static void main(String[] args) { int[] a = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); SelectionSorter sorter = new SelectionSorter(a); sorter.sort(); ArrayUtil.print(a); } } public class SelectionSorter{ public SelectionSorter(int[] anArray) { a = anArray; } public void sort() { for (int i = 0; i < a.length - 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } } //Finds the smallest element in a tail range of the array. private int minimumPosition(int from) { int minPos = from; for (int i = from + 1; i < a.length; i++) if (a[i] < a[minPos]) minPos = i; return minPos; } private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } private int[] a; } Selection Sort Complexity of the algorithms • All the previous algorithms have time complexity (number of steps of computation) O(n2) where n is the number of numbers to sort – See next slide for an example • Better (faster) algorithms? – E.g., Merge Sort Selection sort on arrays of various sizes 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: /** This class sorts an array, using the merge sort algorithm. */ public class MergeSorter { /** Constructs a merge sorter. @param anArray the array to sort */ public MergeSorter(int[] anArray) { a = anArray; } Merge Sort /** Sorts the array managed by this merge sorter. */ public void sort() { if (a.length <= 1) return; int[] first = new int[a.length / 2]; int[] second = new int[a.length - first.length]; System.arraycopy(a, 0, first, 0, first.length); System.arraycopy(a, first.length, second, 0, second.length); MergeSorter firstSorter = new MergeSorter(first); MergeSorter secondSorter = new MergeSorter(second); firstSorter.sort(); secondSorter.sort(); merge(first, second); } 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: /** Merges two sorted arrays into the array managed by this merge sorter. @param first the first sorted array @param second the second sorted array Merge Sort */ private void merge(int[] first, int[] second) { // Merge both halves into the temporary array int iFirst = 0; // Next element to consider in the first array int iSecond = 0; // Next element to consider in the second array int j = 0; // Next open position in a // As long as neither iFirst nor iSecond past the end, move // the smaller element into a while (iFirst < first.length && iSecond < second.length) { if (first[iFirst] < second[iSecond]) { a[j] = first[iFirst]; iFirst++; } else { a[j] = second[iSecond]; iSecond++; } 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: } j++; } Merge Sort // Note that only one of the two calls to arraycopy below // copies entries // Copy any remaining entries of the first array System.arraycopy(first, iFirst, a, j, first.length - iFirst); // Copy any remaining entries of the second half System.arraycopy(second, iSecond, a, j, second.length - iSecond); } private int[] a; 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: /** This program tests the merge sort algorithm by sorting an array that is filled with random numbers. */ public class MergeSortTester { public static void main(String[] args) { int[] a = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); MergeSorter sorter = new MergeSorter(a); sorter.sort(); ArrayUtil.print(a); } } Merge Sort Tester Merge Sort vs. Selection Sort • Selection sort is an O(n2) algorithm • Merge sort is an O(nlog(n)) algorithm • The nlog(n) function grows much more slowly than n2 Sorting in a Java Program • The Arrays class implements a sorting method • To sort an array of integers int[] a = . . . ; Arrays.sort(a); • That sort method uses the Quicksort algorithm import java.util.Random; import java.util.Arrays; Using built-in sort public class BuiltInSort{ public static void main(String[] args){ String[] alphas = {"zulu", "yankee", ”x-ray", "whisky", "victor", "uniform", "tango", "sierra"}; System.out.print("Initial : "); printArray(alphas); sortArray(alphas, true); // true refers to printing after each pass System.out.print("Final : "); printArray(alphas); } public static void printArray( String[] ra){ for (int i = 0 ; i < ra.length ; i++ ){ System.out.print(ra[i]); System.out.print("\t"); } System.out.println(""); // Start a new line } public static void sortArray(String[] ra, boolean printAfterPass){ Arrays.sort(ra); } } Searching • Linear search: also called sequential search • Examines all values in an array until it finds a match or reaches the end • Number of visits for a linear search of an array of n elements: – The average search visits n/2 elements – The maximum visits is n • A linear search locates a value in an array in O(n) steps 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: /** A class for executing linear searches through an array. */ public class LinearSearcher { /** Constructs the LinearSearcher. @param anArray an array of integers */ public LinearSearcher(int[] anArray) { a = anArray; } /** Finds a value in an array, using the linear search algorithm. @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 int search(int v) { for (int i = 0; i < a.length; i++) { if (a[i] == v) return i; } return -1; } private int[] a; } Linear Search 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: import java.util.Scanner; Tester /** This program tests the linear search algorithm. */ public class LinearSearchTester { public static void main(String[] args) { // Construct random array int[] a = ArrayUtil.randomIntArray(20, 100); ArrayUtil.print(a); LinearSearcher searcher = new LinearSearcher(a); Scanner in = new Scanner(System.in); boolean done = false; while (!done) { System.out.print("Enter number to search for, -1 to quit: "); int n = in.nextInt(); if (n == -1) done = true; else { int pos = searcher.search(n); System.out.println("Found in position " + pos); } } } } Binary Search • Locates a value in a sorted array by – Determining whether the value occurs in the first or second half – Then repeating the search in one of the halves 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: /** A class for executing binary searches through an array. */ public class BinarySearcher { /** Constructs a BinarySearcher. @param anArray a sorted array of integers */ public BinarySearcher(int[] anArray) { a = anArray; } Binary Search 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: } 43: /** Finds a value in a sorted array, using the binary search algorithm. @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 int search(int v) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high) / 2; int diff = a[mid] - v; if (diff == 0) // a[mid] == v return mid; else if (diff < 0) // a[mid] < v low = mid + 1; else high = mid - 1; } return -1; } private int[] a; Binary Search A O(log(n)) algorithm import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ObjectsSort extends JApplet implements ActionListener{ JTextArea outputArea; JLabel l1, l2; JTextField t1, t2; JButton b1, b2; Student s, array[]; int stCount=0; public void init() { outputArea = new JTextArea(10,15); l1=new JLabel("Enter student name"); l2=new JLabel("Enter student’s mark"); t1= new JTextField(10); t2= new JTextField(10); JPanel p1=new JPanel(); b1= new JButton("Enter student data"); b2= new JButton("Display students"); array = new Student [100]; Container container = getContentPane(); b1.addActionListener(this); b2.addActionListener(this); Sorting an array of objects p1.setLayout(new GridLayout( 3, 2 ) ); Sorting an p1.add(l1); array of objects p1.add(t1); p1.add(l2); p1.add(t2); p1.add(b1); p1.add(b2); container.add( p1, BorderLayout.NORTH); container.add( new JScrollPane(outputArea), BorderLayout.CENTER ); } public void actionPerformed(ActionEvent e){ String s1="", s2=""; if (e.getSource()==b1){ s1=t1.getText(); s2=t2.getText(); int mark= Integer.parseInt(s2); array[stCount++] = new Student (s1, mark); t1.setText(""); t2.setText(""); } else if (e.getSource()==b2) { String output = "Student records with marks in descending order:\n"; bubbleSort( array ); // sort array // append sorted array values to String output for ( int counter = 0; counter < stCount; counter++ ) output +=array[counter].toString(); outputArea.setText( output ); } } // sort elements of array with marks in descending order Sorting an public void bubbleSort( Student array2[] ) { array of objects // loop to control number of passes for ( int pass = 1; pass < stCount; pass++ ) { // loop to control number of comparisons for ( int element = 0; element < stCount - 1; element++ ) { // compare side-by-side elements and swap them if first // element is greater than second element if ( array2[ element ].getMark() < array2[ element + 1 ].getMark() ) swap( array2, element, element + 1 ); } } } // swap two elements of an array.. we swap references only public void swap( Student array3[], int first, int second ) Student hold; // temporary holding reference for swap hold = array3[ first ]; array3[ first ] = array3[ second ]; array3[ second ] = hold; } } // end of class { class Student { private String name; private int mark; public Student (String n, int m){ name=n; mark=m; } public int getMark() { return mark; } public String getName() { return name; } public String toString() { return name + " has " + mark + "\n"; } } Sorting an array of objects Sorting with names? • Use if (array2[ element ].getName().compareTo(array2[ element + 1 ].getName()) > 0 ) The Comparable Interface • Several classes in Java (e.g. String and Date) implement Comparable • You can implement Comparable interface for your own classes public class Coin implements Comparable { public int compareTo(Object otherObject) { Coin other = (Coin) otherObject; if (value < other.value) return -1; if (value == other.value) return 0; return 1; } ... } Sorting with Comparables • Once your class implements Comparable, simply use the Arrays.sort method: Coin[] coins = new Coin[n]; // Add coins ... Arrays.sort(coins);