I was doing this problem on leetcode and have created this solution for it in java and it was submitted successfully.
class Solution {
public int searchInsert(int[] nums, int val) {
for(int i=0;i<nums.length;i++){
if(nums[i]!=val){
if(nums[i]>val){
return i;
}
}
if(nums[i]==val)
return i;
if(i==nums.length-1 && nums[i]!=val)
return i+1;
}
return 0;
}
}
And when I checked it solution over the google I found a binary search solution which is this
class Test
{
// Simple binary search algorithm
static int binarySearch(int arr[], int l, int r, int x)
{
if (r>=l)
{
int mid = l + (r - l)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
return binarySearch`enter code here`(arr, mid+1, r, x);
}
return -1;
}
I want to ask that, Is my approach is poor than the below binary search approach?