A day leetCode question - an array --35-- Search Insert location

Given a sorted array and a target value, the target value found in the array, and returns its index, if not present in the target array, it will be returned in sequence inserted position.

Suppose the array without the repeating element

Example 1:

Input: [1,3,5,6], 5

Output: 2

Example 2:

Input: [1,3,5,6], 7

Output; 4

Examine a binary search

static int searchInsert(int* nums,int numSize, int target)
{
	int i = 0;
	int j = numSize - 1;
	int mid = 0;

	if (numSize == 0) return numSize;

	while (i<=j)
	{
		mid = (i + j) >> 1;

		if (nums[mid] == target)
		{
			return mid;
		}
		else if (nums[mid] > target)
		{
			j = mid - 1;
		}
		else
		{
			i = mid + 1;
		}
	}
	return i;
}

int main()
{
	int arr[] = {1,2,4,5,9};
	int mid = searchInsert(arr, sizeof(arr) / sizeof(arr[0]),10);
	printf("%d\n", mid);

	system("pause");
	return 0;
}
Published 43 original articles · won praise 1 · views 2299

Guess you like

Origin blog.csdn.net/lpl312905509/article/details/104047854