Home > Net >  Binary Search returning -1 in spite of the element existing
Binary Search returning -1 in spite of the element existing

Time:02-05

For this program, I'm trying to use Binary searching to find a specific element of a given array, such as title, year, or artist. For now, I'm only testing for title and year since they are both strings. But it seems that for some of the input I put in, the program would return -1, even though the input I put in exists on the array. I'm not sure why this happens.

First is the tester class, second code is the constructor class.

public class TestMusic
{
    public static void printMusic(Music[] arr)
    {
        for (Music music : arr)
        {
            System.out.println(music.toString());
        }
    }
    
    public static int binaryTitle(Music[] arr, String title)
    {
        int l = 0, r = arr.length - 1;
        while (l <= r) {
            int m = l   (r - l) / 2;

            int res = title.compareTo(arr[m].getTitle());

            // Check if x is present at mid
            if (res == 0)
                return m;

            // If x greater, ignore left half
            if (res > 0)
                l = m   1;

                // If x is smaller, ignore right half
            else
                r = m - 1;
        }

        return -1;
    }
       

    
    public static int binaryArtist(Music[] arr, String artist)
    {
        int l = 0, r = arr.length - 1;
        while (r - l >= 1) {
            int m = l   (r-l) / 2;

            int res = artist.compareTo(arr[m].getArtist());

            
            if (res == 0)
            {
                return m;
            }

            if (res > 0)
            {
                l = m   1;
            }

            else
            {
                r = m - 1;
            }
        }

        return -1;
    }
    
    public static void main(String[]args)
    {
        Music[] arr = new Music[12];
        arr[0] =  new Music("Montero", 2021, "Lil Nas X");
        arr[1] =  new Music("Dynamite", 2020, "BTS");
        arr[2] =  new Music("Bad Guy", 2019, "Billie Eilish");
        arr[3] =  new Music("Sicko Mode", 2018, "Travis Scott");
        arr[4] =  new Music("Shape of You", 2017, "Ed Sheeran");
        arr[5] =  new Music("Heathens", 2016, "Twenty One Pilots");
        arr[6] =  new Music("See You Again", 2015, "Wiz Khalifa");
        arr[7] =  new Music("All About That Bass", 2014, "Meghan Trainor");
        arr[8] =  new Music("Wrecking Ball", 2013, "Miley Cyrus");
        arr[9] =  new Music("Paradise", 2011, "Coldplay");
        arr[10] = new Music("Shake it Off", 2014, "Taylor Swift");
        arr[11] = new Music("Savage", 2021, "Aespa");
        
        System.out.println("Original:");
        printMusic(arr);
        
        
        
        System.out.println("\nBinary searching Sicko Mode: Index "   binaryTitle(arr, "Sicko Mode"));
        System.out.println("\nBinary searching Taylor Swift: Index "   binaryArtist(arr, "Taylor Swift"));
        
        
        
        
        
    }
}
public class Music
{
    // instance variables
    private int year;
    private String title;
    private String artist;

    // Constructor for objects of class Music
    public Music(String t, int y, String a)
    {
        // initialize instance variables
        title = t;
        year = y;
        artist = a;
    }

    public String getTitle()
    {
        return title;
    }
   
    public void setTitle(String t)
    {
        title = t;
    }
   
    public String getArtist()
    {
        return artist;
    }
    
    public void setArtist(String a)
    {
        artist = a;
    }
   
    public int getYear()
    {
        return year;
    }
    
    public void setTitle(int y)
    {
        year = y;
    }
   
    public String toString()
    {
        String str = String.format( "%-25s M   %-20s ", title,  year , artist);
        return str;
    }
}

CodePudding user response:

for a binary search to work correctly it must be sorted in some way. If you're searching it by year you need to sort it from smallest to largest. if you're searching it by Title, those Titles must be in some alphabetical order, same with the Artist. Ex:

{1,4,3,2,5} //searching for 4 returns -1 because it's looking between 3 and 5 and only finding 2.
{1,2,3,4,5} //searching for 4 returns 3 because it looks between 3 and 5 and finds 4 at index 3.

CodePudding user response:

Binary search requires a sorted array. If you use an array that's not sorted, binary search is liable to not find what you need. For this type of thing you need a sequential search.

Example:

[0, 3, 7, 8, 12, 56, 2]
//say you have this array, and you're looking for number 2,
//your function will compare 2 to the middle element: 8. 
//2 < 8, so it will throw out everything above 8. 
[0, 3, 7]
//Obviously 2 is not there. But it was there originally.
//The problem is it was unsorted

CodePudding user response:

I can confirm that you can only do a type of binary search to its corresponding sort. So title binary search can only happen after a title sort.

  •  Tags:  
  • Related