c # binary search algorithm

Binary search algorithm that is binary search, for example, look at how much an ordered array target number should be inserted into the array indexes are?

Suppose an array as follows:

int[] nums =  { 1, 3, 5, 6 };

To calculate the index value of the target value is inserted into the array. The beginning of the idea:

1. The first target number is inserted into the array

2. Sort

3. Return Index

code show as below:

  public int SearchInsert(int[] nums, int target) {
 int index = System.Array.IndexOf(nums, target);
        if(index>=0)
        {
            return index;
        }else
        {
            List<int> list = nums.ToList();
            list.Insert(nums.Length,target);
            nums = list.ToArray();
            System.Array.Sort(nums,(num1,num2)=>{return num1-num2;});
            return System.Array.IndexOf(nums, target);
        }
    }

Learning can be used later to solve the dichotomy, as follows:

 public  static  int SearchInsert ( int [] the nums, int target) {
         int Start = 0 ; // start index 
        int End nums.Length = - . 1 ; // End index 
        int MID = 0 ; // get intermediate index 
        the while (Start < = End) 
        { 
            MID = Start + (End - Start) / 2 ;
             IF (target == the nums [MID]) { return MID;}
             IF (the nums [MID]> target) 
            {
                end = mid - 1;
            }
            else if (nums[mid] < target)
            {
                start = mid + 1;

            }
        }
        return start;
    }

Code analysis:

The idea is to find binary

1. Define the Look. start, end and end index starting index

2. binary narrow down i.e. mid = start + (end - start) / 2; prevent numeric overflow

If the destination number is greater than half the number, the number will have to be inserted in the right half of the range, it is necessary to find the start of the change start = mid + 1; i.e., after the number of the next half

If the destination number is less than half the number, the number will have to be inserted in the left half, then it is necessary to find the end of the range is reduced to end = mid-1; i.e., a number of the front half

3. have not found a binary needs to be halved again, repeat steps 2

 

Guess you like

Origin www.cnblogs.com/97310ZT/p/10974279.html