Giter Club home page Giter Club logo

Comments (10)

shftdlt avatar shftdlt commented on June 30, 2024

In addition, would it be better to add boundary check to the bottom of the while block as follows:

//searched through the whole array but not found
if (elementToCheck == 0 || elementToCheck == array.length-1) {
    return -1;
}

from algorithms-sedgewick-wayne.

reneargento avatar reneargento commented on June 30, 2024

Thanks for the contribution.
I added the boundary check at the end of the loop.

I am not sure I understand your first comment though. If we update fibonacciBeforeN and fibonacciN at that point, we would be updating them twice. They are also updated at the beginning of the loop.

from algorithms-sedgewick-wayne.

shftdlt avatar shftdlt commented on June 30, 2024

Based on the comment put in chapter1/section4/Exercise22_BinarySearchAddSub.java:

// Based on http://algs4.cs.princeton.edu/14analysis/:
// Answer: Instead of searching based on powers of two (binary search),
// use Fibonacci numbers (which also grow exponentially).
// Maintain the current search range to be [i, i + F(k)] and keep F(k), F(k-1) in two variables.
// At each step compute F(k-2) via subtraction, check element i + F(k-2),
// and update the range to either [i, i + F(k-2)] or [i + F(k-2), i + F(k-2) + F(k-1)].

For the search range [i, i + F(k)], after checking element i + F(k-2), the next search range will be updated to either [i, i + F(k-2)] or [i + F(k-2), i + F(k-2) + F(k-1)].

If the next search range is [i, i + F(k-2)], based on the description of the algorithm(the third & fourth lines of the comment above), F(new k) is actually F(k-2), thus F(new k-1) should be F(k-3) and F(new k-2) should be F(k-4), meaning "fibonacciN" and "fibonacciBeforeN" should be both updated twice.

from algorithms-sedgewick-wayne.

reneargento avatar reneargento commented on June 30, 2024

Are we not going to skip ranges when updating fibonacciN and fibonacciBeforeN twice?
I did a test changing

if (key < array[elementToCheck]) {
    high = low + fibonacciBeforeN;
}

to

if (key < array[elementToCheck]) {
    high = low + fibonacciBeforeN;

    aux = fibonacciBeforeN;
    fibonacciBeforeN = fibonacciN - fibonacciBeforeN; // F(k-2)
    fibonacciN = aux; // F(k-1)
}

and the last test fails (the -2 element is not found in the search).

from algorithms-sedgewick-wayne.

shftdlt avatar shftdlt commented on June 30, 2024

It's caused by still trying to shrink next search range through fibonacci subtraction after F(k) = 1 and F(k-1) = 1, in which case F(k-2) is already 0 (corresponding range was either [i, i] or [i, i + 1]).

In addition, after checking element i + F(k-2), can we update the range to either [i, i + F(k-2) - 1] or [i + F(k-2) + 1, i + F(k-2) + F(k-1)], because i + F(k-2) is already checked?

from algorithms-sedgewick-wayne.

shftdlt avatar shftdlt commented on June 30, 2024

Post my code for your review:

private int binarySearch(int[] array, int key) {
    int aux;
    int fibonacciBeforeN = 0;
    int fibonacciN = 1;

    // Compute F(k)
    while (fibonacciN < array.length - 1) {
        aux = fibonacciN;
        fibonacciN = fibonacciBeforeN + fibonacciN;
        fibonacciBeforeN = aux;
    }

    int low = 0;
    int high = low + array.length - 1;

    while (low <= high) {
        if (fibonacciBeforeN > 0) {
            // Compute F(k-2)
            aux = fibonacciBeforeN;
            fibonacciBeforeN = fibonacciN - fibonacciBeforeN; // F(k-2)
            fibonacciN = aux; // F(k-1)
        }

        int elementToCheck = low + fibonacciBeforeN;
        if (elementToCheck > high) {
            elementToCheck = high;
        }

        if (key < array[elementToCheck]) {
            high = elementToCheck - 1;

            // shrink range one more step
            if (fibonacciBeforeN > 0) {
                // Compute F(k-2)
                aux = fibonacciBeforeN;
                fibonacciBeforeN = fibonacciN - fibonacciBeforeN; // F(k-2)
                fibonacciN = aux; // F(k-1)
            }
        } else if (key > array[elementToCheck]) {
            low = elementToCheck + 1;
        } else {
            return elementToCheck;
        }
    }

    return -1;
}

from algorithms-sedgewick-wayne.

shftdlt avatar shftdlt commented on June 30, 2024

Test cases:

public static void main(String... args) {
    Exercise22_BinarySearchAddSub exercise22_binarySearchAddSub = new Exercise22_BinarySearchAddSub();

    int N = 30;

    for (int i = 1; i <= N; i++) {
        int[] array = IntStream.iterate(2, e -> e + 2).limit(i).toArray();
        int M = (i << 1) + 1;

        for (int j = 1; j <= M; j++) {
            StdOut.print(Arrays.toString(array));
            int index = exercise22_binarySearchAddSub.binarySearch(array, j);
            StdOut.printf(" KEY: %5d; INDEX: %5d\n", j, index);
        }

        StdOut.println();
    }
}

from algorithms-sedgewick-wayne.

shftdlt avatar shftdlt commented on June 30, 2024

Another version for your reference.

private int binarySearch(int[] array, int key) {
    int aux;
    int fibonacciBeforeN = 0;
    int fibonacciN = 1;

    // Compute F(k)
    while (fibonacciN < array.length - 1) {
        aux = fibonacciN;
        fibonacciN = fibonacciBeforeN + fibonacciN;
        fibonacciBeforeN = aux;
    }

    int low = 0;
    int high = array.length - 1;

    while (low <= high) {
        while (fibonacciBeforeN > 0 && fibonacciN >= high - low) {
            // Compute F(k-2)
            aux = fibonacciBeforeN;
            fibonacciBeforeN = fibonacciN - fibonacciBeforeN; // F(k-2)
            fibonacciN = aux; // F(k-1)
        }

        int elementToCheck = low + fibonacciBeforeN;

        if (key < array[elementToCheck]) {
            high = elementToCheck - 1;
        } else if (key > array[elementToCheck]) {
            low = elementToCheck + 1;
        } else {
            return elementToCheck;
        }
    }

    return -1;
}

from algorithms-sedgewick-wayne.

shftdlt avatar shftdlt commented on June 30, 2024

Thanks for the contribution.
I added the boundary check at the end of the loop.

I am not sure I understand your first comment though. If we update fibonacciBeforeN and fibonacciN at that point, we would be updating them twice. They are also updated at the beginning of the loop.

Sorry for my mention of bottom check above, it's actually a defect. For array [2, 4] and key 2, the search result is -1, which is not correct.

from algorithms-sedgewick-wayne.

reneargento avatar reneargento commented on June 30, 2024

With the latest changes the code seems to be working well.
I updated the exercise here: 6b35bd2
Thanks for the contribution!

from algorithms-sedgewick-wayne.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.