Java BinarySearch

前端 未结 10 2143
忘了有多久
忘了有多久 2020-12-09 23:33

Can I get some help please? I have tried many methods to get this to work i got the array sorted and to print but after that my binary search function doesnt want to run and

10条回答
  •  Happy的楠姐
    2020-12-09 23:55

    int binarySearch(int list[], int lowIndex, int highIndex, int find)
        {
            if (highIndex>=lowIndex)
            {
                int mid = lowIndex + (highIndex - lowIndex)/2;
    
                // If the element is present at the
                // middle itself
                if (list[mid] == find)
                    return mid;
    
                // If element is smaller than mid, then
                // it can only be present in left subarray
                if (list[mid] > find)
                    return binarySearch(list, lowIndex, mid-1, find);
    
                // Else the element can only be present
                // in right subarray
                return binarySearch(list, mid+1, highIndex, find);
            }
    
            // We reach here when element is not present
            //  in array
            return -1;
        }
    

提交回复
热议问题