简体   繁体   中英

How to find last element in an array by specific key

i have to find the first and the last element by a specific key (with a binary search method). I'm already done with the searchFirst method but i'm not able to complete the searchLast method. Sometimes it works sometimes it doesn't (it depends with value im looking for) and thats the problem.

I have a Data class with some atributes like timestamp, name, product, etc. which im reading out of a text file. When im done with filling the Data array im sorting the array with a merge sort.

Then i need the first and last element of the Array by a specific name.

The searchFirst method works perfect but the searchLast won't do what i want.

Here's the code of the searchLast method(n is the value he should look for and w isn't used at the moment).

public static int searchLast(Data[] array, String n, String w) {
        int left = 0;
        int right = array.length - 1;
        int m = -1;

        while (left < right) {
            m = (left + right) / 2;
            if (array[m].getName().compareTo(n) > 0) {
                right = m - 1;
            } else {
                left = m + 1;
            }
        }

        if (m >= 0) {
            if (array[right].getName().equals(n)) {
                return right;
            }
        }

        return NO_KEY;
    }

I can't find the bug maybe you could help me... Sometimes the code finds the last one sometimes it doesn't...

public static int searchLast(Data[] array, String n, String w) {
        int left = 0;
        int right = array.length - 1;
        int m = -1;
        int found = -1;

            while (left < right) {
                m = (left + right) / 2;
                if (array[m].getName().compareTo(n) > 0) {
                    right = m - 1;
                } else if (array[m].getName().compareTo(n) < 0){
                    left = m + 1;
                } else {
                    found = m;
                    left = m + 1;
            }

        return found;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM