Search code examples
c#binary-search

Write a program in C# which uses Iterative Binary Search algorithm to search age of the person using his / her name


This requires splitting the array which contains age and name of the person, and then performing search operation on the name variable and finally print the age if the name is present in the array.

So, far I have only created a 2D array but don't know how to split and then perform the search

String[,] arr = { { "aakif", "25" }, {"ali", "31"} , {"ben","35"}, {"hassnain" ,"45" } };

Solution

  • I do disagree with the way you store your input but you can achieve your search with the following:

    String[,] arr = new string[2,4];
    arr[0, 0] = "saif";
    arr[0, 1] = "25";
    arr[0, 2] = "ali";
    arr[0, 3] = "17";
    arr[1, 0] = "aakif";
    arr[1, 1] = "11";
    arr[1, 2] = "hassnain";
    arr[1, 3] = "50";
    
    int index = -1;
    int jindex = -1;
    for ( int i =0 ; i <arr.GetLength(0) ; i++) {
        for ( int j =0 ; j <arr.GetLength(1) ; j++) {
            if (arr[i,j]== "ali")   {
                index = i;
                jindex = j;
                break;
            }
    
        }
    }
    
    if ( index != -1) {
        Console.WriteLine(arr[index,jindex] + " " + arr[index,jindex +1 ]);
    }
    else Console.WriteLine("Not Found");