Fibonacci Sequence - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

Fibonacci Sequence

Description:

A tester program used to generate and print ... Merge Sort Tester. Merge Sort vs. Selection Sort. Selection sort is ... Tester. Binary Search. Locates a value in ... – PowerPoint PPT presentation

Number of Views:161
Avg rating:3.0/5.0
Slides: 31
Provided by: Office2004748
Category:

less

Transcript and Presenter's Notes

Title: Fibonacci Sequence


1
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

2
01 import java.util.Scanner02 03 /04
This program computes Fibonacci numbers using a
recursive05 method.06 / 07 public class
FibTester08 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 lt
n i)16 17 long f
fib(i)18 System.out.println("fib("
i ") " f)19 20 21 22
/23 Computes a Fibonacci number.24
_at_param n an integer25 _at_return the nth
Fibonacci number26 /27 public static
long fib(int n)28 29 if (n lt 2)
return 130 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

3
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 lt 2
  • If (n lt 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

4
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

5
// 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 lt 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 lt array.length
counter ) output " " array
counter outputArea.setText( output )
setSize( 375, 200 ) setVisible( true
  • Bubble Sort

6
// sort elements of array with bubble sort
public void bubbleSort( int array2 )
// loop to control number of passes for (
int pass 1 pass lt array2.length pass )
// loop to control number of comparisons
for ( int element 0 element lt
array2.length - 1 element )
// compare side-by-side elements and swap them if
// first element is greater than second
element if ( array2 element gt
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.setDefaultCl
oseOperation(JFrame.EXIT_ON_CLOSE) //
end class BubbleSort
  • Bubble Sort

7
public class InsertionSorter public
InsertionSorter(int anArray) a
anArray public void sort()
for (int i 1 i lt a.length i)
int next ai // Move all larger
elements up int j i while (j
gt 0 aj - 1 gt next) aj aj
- 1 j-- //
Insert the element aj next
private int a
  • Insertion Sort

8
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 lt
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 lt
a.length i) if (ai lt aminPos)
minPos i return minPos private
void swap(int i, int j) int temp
ai ai aj aj temp
private int a
  • Selection Sort

9
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

10
Selection sort on arrays of various sizes
11
01 /02 This class sorts an array, using
the merge sort algorithm.03 /04 public class
MergeSorter05 06 /07 Constructs
a merge sorter.08 _at_param anArray the
array to sort09 /10 public
MergeSorter(int anArray)11 12 a
anArray13 14 15 /16
Sorts the array managed by this merge sorter.17
/18 public void sort()19 20
if (a.length lt 1) return21 int
first new inta.length / 222 int
second new inta.length - first.length23
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 this34 merge sorter.
35 _at_param first the first sorted
array36 _at_param second the second sorted
array37 /38 private void merge(int
first, int second)39 40 //
Merge both halves into the temporary array41
42 int iFirst 043 // Next
element to consider in the first array44
int iSecond 045 // Next element to
consider in the second array46 int j 0
47 // Next open position in a48 49
// As long as neither iFirst nor iSecond
past the end, move50 // the smaller
element into a51 while (iFirst lt
first.length iSecond lt second.length)52
53 if (firstiFirst lt
secondiSecond)54 55
aj firstiFirst56
iFirst57 58 else59
60 aj
secondiSecond61 iSecond62
63 j64 65 66
// Note that only one of the two calls to
arraycopy below67 // copies entries68
69 // Copy any remaining entries of the
first array70 System.arraycopy(first,
iFirst, a, j, first.length - iFirst)71
72 // Copy any remaining entries of the
second half73 System.arraycopy(second,
iSecond, a, j, second.length - iSecond)74
75 76 private int a77
  • Merge Sort

12
32 /33 Merges two sorted arrays
into the array managed by this34 merge
sorter. 35 _at_param first the first sorted
array36 _at_param second the second sorted
array37 /38 private void merge(int
first, int second)39 40 //
Merge both halves into the temporary array41
42 int iFirst 043 // Next
element to consider in the first array44
int iSecond 045 // Next element to
consider in the second array46 int j 0
47 // Next open position in a48 49
// As long as neither iFirst nor iSecond
past the end, move50 // the smaller
element into a51 while (iFirst lt
first.length iSecond lt second.length)52
53 if (firstiFirst lt
secondiSecond)54 55
aj firstiFirst56
iFirst57 58 else59
60 aj
secondiSecond61 iSecond62
  • Merge Sort

13
63 j64 65 66 //
Note that only one of the two calls to arraycopy
below67 // copies entries68 69
// Copy any remaining entries of the first
array70 System.arraycopy(first, iFirst,
a, j, first.length - iFirst)71 72
// Copy any remaining entries of the second
half73 System.arraycopy(second, iSecond,
a, j, second.length - iSecond)74 75 76
private int a77
  • Merge Sort

14
01 /02 This program tests the merge sort
algorithm by03 sorting an array that is
filled with random numbers.04 /05 public
class MergeSortTester06 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

15
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

16
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

17
import java.util.Randomimport 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
lt ra.length i ) System.out.print(rai
) 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

18
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

19
01 /02 A class for executing linear
searches through an array.03 /04 public
class LinearSearcher05 06 /07
Constructs the LinearSearcher.08 _at_param
anArray an array of integers09 /10
public LinearSearcher(int anArray)11 12
a anArray13 14 15 /16
Finds a value in an array, using the linear
search 17 algorithm.18 _at_param v
the value to search19 _at_return the index
at which the value occurs, or -120 if it
does not occur in the array21 /22
public int search(int v)23 24 for
(int i 0 i lt a.length i)25 26
if (ai v)27 return
i28 29 return -130 31
32 private int a33
  • Linear Search

20
01 import java.util.Scanner02 03 /04
This program tests the linear search
algorithm.05 /06 public class
LinearSearchTester07 08 public static
void main(String args)09 10 //
Construct random array11 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 false19 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 true25 else26
27 int pos searcher.search(n)2
8 System.out.println("Found in
position " pos)29 30 31
32
  • Tester

21
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

22
01 /02 A class for executing binary
searches through an array.03 /04 public
class BinarySearcher05 06 /07
Constructs a BinarySearcher.08 _at_param
anArray a sorted array of integers09 /10
public BinarySearcher(int anArray)11
12 a anArray13 14
  • Binary Search

23
15 /16 Finds a value in a sorted
array, using the binary17 search
algorithm.18 _at_param v the value to
search19 _at_return the index at which the
value occurs, or -120 if it does not
occur in the array21 /22 public int
search(int v)23 24 int low
025 int high a.length - 126
while (low lt high)27 28 int
mid (low high) / 229 int diff
amid - v30 31 if (diff
0) // amid v32 return mid33
else if (diff lt 0) // amid lt v 34
low mid 135 else36
high mid - 1 37 38
return -139 40 41 private
int a42 43
  • Binary Search
  • A O(log(n)) algorithm

24
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 stCount0  public void
init() outputArea new
JTextArea(10,15) l1new JLabel("Enter
student name") l2new JLabel("Enter
students mark") t1 new JTextField(10)
t2 new JTextField(10) JPanel p1new
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

25
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)
s1t1.getText()
s2t2.getText() int mark
Integer.parseInt(s2) arraystCount
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 lt stCount counter )
output arraycounter.toString()
outputArea.setText( output )
  • Sorting an array of objects

26
// 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 lt stCount pass ) // loop
to control number of comparisons for (
int element 0 element lt stCount - 1 element
) // compare side-by-side elements and
swap them if first // element is greater than
second element if ( array2 element
.getMark() lt 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

27
class Student private String name
private int mark public Student (String n,
int m) namen markm
public int getMark() return mark
public String getName() return
name public String toString()
return name " has " mark "\n"
  • Sorting an array of objects

28
Sorting with names?
  • Use
  • if (array2 element .getName().compareTo(array2
    element 1 .getName()) gt 0 )

29
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 lt other.value) return -1
  • if (value other.value) return 0
  • return 1
  • . . .

30
Sorting with Comparables
  • Once your class implements Comparable, simply use
    the Arrays.sort method
  • Coin coins new Coinn
  • // Add coins
  • . . .
  • Arrays.sort(coins)
Write a Comment
User Comments (0)
About PowerShow.com