Question

• Write a JavaFX code that generates Fibonacci number sequence of a certain length (-100 numbers) • The program then uses buc

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Given a sorted array arr[] of size n and an element x to be searched in it. Return index of x if it is present in array else return -1.

Examples:

Input: arr[] = {2, 3, 4, 10, 40}, x = 10

Output: 3

Element x is present at index 3.

Input: arr[] = {2, 3, 4, 10, 40}, x = 11

Output: -1

Element x is not present.

Fibonacci Search is a comparison-based technique that uses Fibonacci numbers to search an element in a sorted array.

Similarities with Binary Search:

Works for sorted arrays

A Divide and Conquer Algorithm.

Has Log n time complexity.

Differences with Binary Search:

Fibonacci Search divides given array in unequal parts

Binary Search uses division operator to divide range. Fibonacci Search doesn’t use /, but uses + and -. The division operator may be costly on some CPUs.

Fibonacci Search examines relatively closer elements in subsequent steps. So when input array is big that cannot fit in CPU cache or even in RAM, Fibonacci Search can be useful.

Background:

Fibonacci Numbers are recursively defined as F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1. First few Fibinacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

Observations:

Below observation is used for range elimination, and hence for the O(log(n)) complexity.

F(n - 2) ≈ (1/3)*F(n) and

F(n - 1) ≈ (2/3)*F(n).

Algorithm:

Let the searched element be x.

The idea is to first find the smallest Fibonacci number that is greater than or equal to the length of given array. Let the found Fibonacci number be fib (m’th Fibonacci number). We use (m-2)’th Fibonacci number as the index (If it is a valid index). Let (m-2)’th Fibonacci Number be i, we compare arr[i] with x, if x is same, we return i. Else if x is greater, we recur for subarray after i, else we recur for subarray before i.

Below is the complete algorithm

Let arr[0..n-1] be the input array and element to be searched be x.

Find the smallest Fibonacci Number greater than or equal to n. Let this number be fibM [m’th Fibonacci Number]. Let the two Fibonacci numbers preceding it be fibMm1 [(m-1)’th Fibonacci Number] and fibMm2 [(m-2)’th Fibonacci Number].

While the array has elements to be inspected:

Compare x with the last element of the range covered by fibMm2

If x matches, return index

Else If x is less than the element, move the three Fibonacci variables two Fibonacci down, indicating elimination of approximately rear two-third of the remaining array.

Else x is greater than the element, move the three Fibonacci variables one Fibonacci down. Reset offset to index. Together these indicate elimination of approximately front one-third of the remaining array.

Since there might be a single element remaining for comparison, check if fibMm1 is 1. If Yes, compare x with that remaining element. If match, return index.

// Java program for Fibonacci Search

import java.util.*;

  

class Fibonacci

{   

// Utility function to find minimum  

// of two elements

public static int min(int x, int y)  

{ return (x <= y)? x : y; }

  

/* Returns index of x if present, else returns -1 */

public static int fibMonaccianSearch(int arr[],  

int x, int n)

{

/* Initialize fibonacci numbers */

int fibMMm2 = 0; // (m-2)'th Fibonacci No.

int fibMMm1 = 1; // (m-1)'th Fibonacci No.

int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci

  

/* fibM is going to store the smallest  

Fibonacci Number greater than or equal to n */

while (fibM < n)

{

fibMMm2 = fibMMm1;

fibMMm1 = fibM;

fibM = fibMMm2 + fibMMm1;

}

  

// Marks the eliminated range from front

int offset = -1;

  

/* while there are elements to be inspected.  

Note that we compare arr[fibMm2] with x.  

When fibM becomes 1, fibMm2 becomes 0 */

while (fibM > 1)

{

// Check if fibMm2 is a valid location

int i = min(offset+fibMMm2, n-1);

  

/* If x is greater than the value at  

index fibMm2, cut the subarray array  

from offset to i */

if (arr[i] < x)

{

fibM = fibMMm1;

fibMMm1 = fibMMm2;

fibMMm2 = fibM - fibMMm1;

offset = i;

}

  

/* If x is less than the value at index  

fibMm2, cut the subarray after i+1 */

else if (arr[i] > x)

{

fibM = fibMMm2;

fibMMm1 = fibMMm1 - fibMMm2;

fibMMm2 = fibM - fibMMm1;

}

  

/* element found. return index */

else return i;

}

  

/* comparing the last element with x */

if(fibMMm1 == 1 && arr[offset+1] == x)

return offset+1;

  

/*element not found. return -1 */

return -1;

}

  

// driver code

public static void main(String[] args)

{

int arr[] = {10, 22, 35, 40, 45, 50,  

80, 82, 85, 90, 100};

int n = 11;

int x = 85;

System.out.print ("Found at index: "+

fibMonaccianSearch(arr, x, n));

}

}

Bucket Sort

Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the following problem.

Sort a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. How do we sort the numbers efficiently?

A simple way is to apply a comparison based sorting algorithm. The lower bound for Comparison based sorting algorithm (Merge Sort, Heap Sort, Quick-Sort .. etc) is Ω(n Log n), i.e., they cannot do better than nLogn.

Can we sort the array in linear time? Counting sort can not be applied here as we use keys as index in counting sort. Here keys are floating point numbers.  

The idea is to use bucket sort. Following is bucket algorithm.

bucketSort(arr[], n)

1) Create n empty buckets (Or lists).

2) Do following for every array element arr[i].

.......a) Insert arr[i] into bucket[n*array[i]]

3) Sort individual buckets using insertion sort.

4) Concatenate all sorted buckets.

0 0.78 07 10.17 1 0.12 0.17 2 0.39 2 0.21 0.23 0.26 / 3 0.26 3 0.39 4 0.72 4 5 0.94 5 / 6 0.21 6 0.68 7 0.12 7 0.72 0.78 7 80Time Complexity: If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm clearly take O(n) time. The O(1) is easily possible if we use a linked list to represent a bucket (In the following code, C++ vector is used for simplicity). Step 4 also takes O(n) time as there will be n items in all buckets.

The main step to analyze is step 3. This step also takes O(n) time on average if all numbers are uniformly distributed

Following is the implementation of the above algorithm.

// Java program to sort an array

// using bucket sort

import java.util.*;

import java.util.Collections;

  

class GFG {

  

// Function to sort arr[] of size n

// using bucket sort

static void bucketSort(float arr[], int n)

{

if (n <= 0)

return;

  

// 1) Create n empty buckets

@SuppressWarnings("unchecked")

Vector<Float>[] buckets = new Vector[n];

  

for (int i = 0; i < n; i++) {

buckets[i] = new Vector<Float>();

}

  

// 2) Put array elements in different buckets

for (int i = 0; i < n; i++) {

float idx = arr[i] * n;

buckets[(int)idx].add(arr[i]);

}

  

// 3) Sort individual buckets

for (int i = 0; i < n; i++) {

Collections.sort(buckets[i]);

}

  

// 4) Concatenate all buckets into arr[]

int index = 0;

for (int i = 0; i < n; i++) {

for (int j = 0; j < buckets[i].size(); j++) {

arr[index++] = buckets[i].get(j);

}

}

}

  

// Driver code

public static void main(String args[])

{

float arr[] = { (float)0.897, (float)0.565,

(float)0.656, (float)0.1234,

(float)0.665, (float)0.3434 };

  

int n = arr.length;

bucketSort(arr, n);

  

System.out.println("Sorted array is ");

for (float el : arr) {

System.out.print(el + " ");

}

Sorted array is

0.1234 0.3434 0.565 0.656 0.665 0.897

Add a comment
Know the answer?
Add Answer to:
• Write a JavaFX code that generates Fibonacci number sequence of a certain length (-100 numbers)...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please write a MIPS program to print the first thirty numbers in the Fibonacci sequence in which each number is the sum of the two preceding ones, starting from 0 and 1. Note that each number in the Fibonacci sequence should be calculated using MIPS instr

    Please write a MIPS program to print the first thirty numbers in the Fibonacci sequence in which each number is the sum of the two preceding ones, starting from 0 and 1. Note that each number in the Fibonacci sequence should be calculated using MIPS instructions. After that please run your MIPS program using SPIM software to display the result in the output (console) window. Save your execution result in a log file of SPIM.What to submit:  1. Your MIPS...

  • need source code for NetBeans here is the file Write a class PrimeSequence that implements the Sequence inte...

    need source code for NetBeans here is the file Write a class PrimeSequence that implements the Sequence interface of Worked Example 10.1* and produces a sequence of prime numbers. * See Files section bj6_ch10_we.pdf Hint: Pseudocode to produce next prime: class Prime Sequence implements Sequence instance variable int p function next ()I isPrime-true While (isPrime) increment p; for (d-2; until d*d > p divides p) isPrime-false; d+) if (d if isPrime) return p; isPrime-true Use your PrimeSequence class to generate...

  • java/javafx assignment: Island Paradise just started running their city lotto. You've been tasked with writing a...

    java/javafx assignment: Island Paradise just started running their city lotto. You've been tasked with writing a program for them. The program is going to allow to user to first select their lotto numbers. The program will then randomly generate the winning lotto numbers for the week and then check the winning numbers against the random ticket the user played in the Lotto to see how many numbers the user guessed correctly. The rules for lotto work as follows: Select 7...

  • Write a program that check odd / even numbers (from number 1 to 100). Display the...

    Write a program that check odd / even numbers (from number 1 to 100). Display the results within an HTML table with 2 columns: one for odd number and one for even numbers. NUMBERS RESULTS ODD EVEN ODD 2 HINT: use <table> tags to create a table, <th> tags for 'Numbers' and 'Results'. Wrap code PHP inside HTML code. For example: <html> <title>CHECK ODD or EVEN</title> <body> <table> ?php echo "<tr><td>l</td><td>Odd</td</tr>"; </table> </body </html 2. Do the following steps in...

  • Create a CodeBlocks project "HW 9" Write the code to ask the user to enter the...

    Create a CodeBlocks project "HW 9" Write the code to ask the user to enter the size of an array. Then create an integer array of that exact size. Ask the user to enter a maximum value and then write a loop to fill the array with random numbers with value in the range of 1 to the maximum value. For example, if the maximum value is 100, random numbers must have value 1 to 100 inclusive. Input size of...

  • AA. Final Project - Improved JavaFX GUI Personal Lending Library Description: In this project we will...

    AA. Final Project - Improved JavaFX GUI Personal Lending Library Description: In this project we will improve our personal lending library tool by (1) adding the ability to delete items from the library, (2) creating a graphical user interface that shows the contents of the library and allows the user to add, delete, check out, or check in an item. (3) using a file to store the library contents so that they persist between program executions, and (4) removing the...

  • Code in JAVA.................... Guess the Number In this activity, you will write a REST server to...

    Code in JAVA.................... Guess the Number In this activity, you will write a REST server to facilitate playing a number guessing game known as "Bulls and Cows". In each game, a 4-digit number is generated where every digit is different. For each round, the user guesses a number and is told the exact and partial digit matches. An exact match occurs when the user guesses the correct digit in the correct position. A partial match occurs when the user guesses...

  • This C++ Program consists of: operator overloading, as well as experience with managing dynamic memory allocation...

    This C++ Program consists of: operator overloading, as well as experience with managing dynamic memory allocation inside a class. Task One common limitation of programming languages is that the built-in types are limited to smaller finite ranges of storage. For instance, the built-in int type in C++ is 4 bytes in most systems today, allowing for about 4 billion different numbers. The regular int splits this range between positive and negative numbers, but even an unsigned int (assuming 4 bytes)...

  • You need not run Python programs on a computer in solving the following problems. Place your...

    You need not run Python programs on a computer in solving the following problems. Place your answers into separate "text" files using the names indicated on each problem. Please create your text files using the same text editor that you use for your .py files. Answer submitted in another file format such as .doc, .pages, .rtf, or.pdf will lose least one point per problem! [1] 3 points Use file math.txt What is the precise output from the following code? bar...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT