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,

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

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.
CMPS1371 Introduction to Computing for Engineers SORTING.
CSE 1302 Lecture 22 Quick Sort and Merge Sort Richard Gesick.
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.
Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters.
1 Lecture 21 Introduction to Sorting I Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.  Brief.
Searching Algorithms. Lecture Objectives Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm To.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
Sorting Algorithms: Selection, Insertion and Bubble.
Data Structures Review Session 1
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.
Searching Arrays Linear search Binary search small arrays
1 Sorting Algorithms (Part I) Sorting Algoritms (Part I) Overview  What is Sorting?  Some Useful Array Handling Methods.  Selection Sort and its Implementation.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
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.
CS 46B: Introduction to Data Structures July 7 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Recursion A recursive computation solves a problem by using the solution of the same problem with simpler values The same computation occurs repeatedly.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
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.
Chapter 19 Searching, Sorting and Big O
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.
Methods Divide and conquer Programmer-declared methods Prepackaged methods – Java API Software reusability Debug-ability and maintainability AKA functions.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 14 – Sorting and Searching.
4/15: Searching Arrays Look at BubbleSort.java Searching arrays: the linear search Searching arrays: the binary search.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
CHAPTER 18 SORTING AND SEARCHING. CHAPTER GOALS To study the several searching and sorting algorithms To appreciate that algorithms for the same task.
Chapter 15: Algorithms 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 15 Algorithms.
SortingBigOh Sorting and "Big Oh" Adapted for ASFA from a presentation by: Barb Ericson Georgia Tech Aug 2007 ASFA AP Computer Science.
SortingBigOh ASFA AP Computer Science A. Big-O refers to the order of an algorithm runtime growth in relation to the number of items I. O(l) - constant.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Selection Sort Sorts an array by repeatedly finding the smallest.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
CS 46B: Introduction to Data Structures July 2 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
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.
11/30: Sorting and Searching Arrays Look at PassArray.java Sorting arrays: the bubble sort method Searching arrays: the linear search Searching arrays:
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
8/8: Sorting and Searching Arrays Look at PassArray.java Sorting arrays: the bubble sort method Searching arrays: the linear search Searching arrays: the.
Lecture 4: Chapter 7 - Arrays Outline Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods.
Using recursion for Searching and Sorting
Sorting and "Big Oh" ASFA AP Computer Science A SortingBigOh.
Lecture 14 Searching and Sorting Richard Gesick.
Ch 14: Search and Sorting Yonglei Tao.
Algorithm design and Analysis
Chapter 19 Sorting and Searching
Lecture 11 Searching and Sorting Richard Gesick.
25 Searching and Sorting Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified.
24 Searching and Sorting.
14 SORTING AND SEARCHING CHAPTER
Chapter 14 – Sorting and Searching
Workshop for CS-AP Teachers
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

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, 34, 55

01: import java.util.Scanner; 02: 03: /** 04: This program computes Fibonacci numbers using a recursive 05: method. 06: */ 07: public class FibTester 08: { 09: public static void main(String[] args) 10: { 11: Scanner in = new Scanner(System.in); 12: System.out.print("Enter n: "); 13: int n = in.nextInt(); 14: 15: for (int i = 1; i <= n; i++) 16: { 17: long f = fib(i); 18: System.out.println("fib(" + i + ") = " + f); 19: } 20: } 21: 22: /** 23: Computes a Fibonacci number. n an integer the nth Fibonacci number 26: */ 27: public static long fib(int n) 28: { 29: if (n <= 2) return 1; 30: else return fib(n - 1) + fib(n - 2); 31: } 32: } 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[ 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 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(n 2 ) 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: This class sorts an array, using the merge sort algorithm. 03: */ 04: public class MergeSorter 05: { 06: /** 07: Constructs a merge sorter. anArray the array to sort 09: */ 10: public MergeSorter(int[] anArray) 11: { 12: a = anArray; 13: } 14: 15: /** 16: Sorts the array managed by this merge sorter. 17: */ 18: public void sort() 19: { 20: if (a.length <= 1) return; 21: int[] first = new int[a.length / 2]; 22: int[] second = new int[a.length - first.length]; 23: System.arraycopy(a, 0, first, 0, first.length); 24: System.arraycopy(a, first.length, second, 0, second.length); 25: MergeSorter firstSorter = new MergeSorter(first); 26: MergeSorter secondSorter = new MergeSorter(second); 27: firstSorter.sort(); 28: secondSorter.sort(); 29: merge(first, second); 30: } 31: 32: /** 33: Merges two sorted arrays into the array managed by this 34: merge sorter. first the first sorted array second the second sorted array 37: */ 38: private void merge(int[] first, int[] second) 39: { 40: // Merge both halves into the temporary array 41: 42: int iFirst = 0; 43: // Next element to consider in the first array 44: int iSecond = 0; 45: // Next element to consider in the second array 46: int j = 0; 47: // Next open position in a 48: 49: // As long as neither iFirst nor iSecond past the end, move 50: // the smaller element into a 51: while (iFirst < first.length && iSecond < second.length) 52: { 53: if (first[iFirst] < second[iSecond]) 54: { 55: a[j] = first[iFirst]; 56: iFirst++; 57: } 58: else 59: { 60: a[j] = second[iSecond]; 61: iSecond++; 62: } 63: j++; 64: } 65: 66: // Note that only one of the two calls to arraycopy below 67: // copies entries 68: 69: // Copy any remaining entries of the first array 70: System.arraycopy(first, iFirst, a, j, first.length - iFirst); 71: 72: // Copy any remaining entries of the second half 73: System.arraycopy(second, iSecond, a, j, second.length - iSecond); 74: } 75: 76: private int[] a; 77: } Merge Sort

32: /** 33: Merges two sorted arrays into the array managed by this 34: merge sorter. first the first sorted array second the second sorted array 37: */ 38: private void merge(int[] first, int[] second) 39: { 40: // Merge both halves into the temporary array 41: 42: int iFirst = 0; 43: // Next element to consider in the first array 44: int iSecond = 0; 45: // Next element to consider in the second array 46: int j = 0; 47: // Next open position in a 48: 49: // As long as neither iFirst nor iSecond past the end, move 50: // the smaller element into a 51: while (iFirst < first.length && iSecond < second.length) 52: { 53: if (first[iFirst] < second[iSecond]) 54: { 55: a[j] = first[iFirst]; 56: iFirst++; 57: } 58: else 59: { 60: a[j] = second[iSecond]; 61: iSecond++; 62: } Merge Sort

63: j++; 64: } 65: 66: // Note that only one of the two calls to arraycopy below 67: // copies entries 68: 69: // Copy any remaining entries of the first array 70: System.arraycopy(first, iFirst, a, j, first.length - iFirst); 71: 72: // Copy any remaining entries of the second half 73: System.arraycopy(second, iSecond, a, j, second.length - iSecond); 74: } 75: 76: private int[] a; 77: } Merge Sort

01: /** 02: This program tests the merge sort algorithm by 03: sorting an array that is filled with random numbers. 04: */ 05: public class MergeSortTester 06: { 07: public static void main(String[] args) 08: { 09: int[] a = ArrayUtil.randomIntArray(20, 100); 10: ArrayUtil.print(a); 11: MergeSorter sorter = new MergeSorter(a); 12: sorter.sort(); 13: ArrayUtil.print(a); 14: } 15: } 16: Merge Sort Tester

Merge Sort vs. Selection Sort Selection sort is an O(n 2 ) algorithm Merge sort is an O(nlog(n)) algorithm The nlog(n) function grows much more slowly than n 2

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; 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); } } Using built-in sort

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: A class for executing linear searches through an array. 03: */ 04: public class LinearSearcher 05: { 06: /** 07: Constructs the LinearSearcher. anArray an array of integers 09: */ 10: public LinearSearcher(int[] anArray) 11: { 12: a = anArray; 13: } 14: 15: /** 16: Finds a value in an array, using the linear search 17: algorithm. v the value to search the index at which the value occurs, or -1 20: if it does not occur in the array 21: */ 22: public int search(int v) 23: { 24: for (int i = 0; i < a.length; i++) 25: { 26: if (a[i] == v) 27: return i; 28: } 29: return -1; 30: } 31: 32: private int[] a; 33: } Linear Search

01: import java.util.Scanner; 02: 03: /** 04: This program tests the linear search algorithm. 05: */ 06: public class LinearSearchTester 07: { 08: public static void main(String[] args) 09: { 10: // Construct random array 11: 12: int[] a = ArrayUtil.randomIntArray(20, 100); 13: ArrayUtil.print(a); 14: LinearSearcher searcher = new LinearSearcher(a); 15: 16: Scanner in = new Scanner(System.in); 17: 18: boolean done = false; 19: while (!done) 20: { 21: System.out.print("Enter number to search for, -1 to quit: "); 22: int n = in.nextInt(); 23: if (n == -1) 24: done = true; 25: else 26: { 27: int pos = searcher.search(n); 28: System.out.println("Found in position " + pos); 29: } 30: } 31: } 32: } Tester

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: A class for executing binary searches through an array. 03: */ 04: public class BinarySearcher 05: { 06: /** 07: Constructs a BinarySearcher. anArray a sorted array of integers 09: */ 10: public BinarySearcher(int[] anArray) 11: { 12: a = anArray; 13: } 14: Binary Search

15: /** 16: Finds a value in a sorted array, using the binary 17: search algorithm. v the value to search the index at which the value occurs, or -1 20: if it does not occur in the array 21: */ 22: public int search(int v) 23: { 24: int low = 0; 25: int high = a.length - 1; 26: while (low <= high) 27: { 28: int mid = (low + high) / 2; 29: int diff = a[mid] - v; 30: 31: if (diff == 0) // a[mid] == v 32: return mid; 33: else if (diff < 0) // a[mid] < v 34: low = mid + 1; 35: else 36: high = mid - 1; 37: } 38: return -1; 39: } 40: 41: private int[] a; 42: } 43: 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 ) ); p1.add(l1); 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 ); } } Sorting an array of objects

// sort elements of array with marks in descending order public void bubbleSort( Student array2[] ) { // 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 Sorting an array of objects

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 Comparable s Once your class implements Comparable, simply use the Arrays.sort method: Coin[] coins = new Coin[n]; // Add coins... Arrays.sort(coins);