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?
The binary search is the better solution to find the insertion point.
Your solution will find the insertion index in O(n)
and the binary search in O(log(n))
.
For context: The time complexity for this kind of algorithem is measured at the number of comparisons the algorithem has to perform.
The difference in complexity comes is because your solution will decrease the width of the search space by 1 in each loop iteration => linear complexity. On the other hand the binary search will cut the search space in half with each recursive call => logarithmic complexity.