[Procedural Basics] Divide and Conquer

Table of contents

Thought

Split an overall problem into multiple sub-problems, and then solve the multiple sub-problems.
The usage scenario must comply with the following:
1. The problem must be split into multiple identical sub-problems
2. The split sub-problems must be independent of each other

Specific steps:
1. Decompose multiple problems into small ones
2. Solve multiple small problems one by one
3. Merge, merge various small problems

merge sort

Merge sort is the most common problem of divide and conquer method

 void MergeSort(int* arr,int len)
    {
    
    
        MergeSort(0,len-1,arr);
    }
    
    void MergeSort(int start,int end,int* arr)
    {
    
    
        if(start >= end){
    
    
            return;
        }

        int mid = start + (end - start) << 1;
        MergeSort(start,mid,arr);
        MergeSort(mid + 1,end,arr);

        //最后合并
        Merge(start,mid,end,arr);
    }

    void Merge(int start,int mid,int end,int* arr)
    {
    
    
        vector<int> tmp;
        int i = start, j = mid + 1;
        while (i<=mid&&j<=end)
        {
    
    
            int t = arr[i] > arr[j] ? arr[j++] : arr[i++];
            tmp.push_back(t);
        }

        while (i<=mid)
        {
    
    
            tmp.push_back(arr[i++]);
        }

        while (j<=end)
        {
    
    
            tmp.push_back(arr[j++]);
        }

        for(i = start,j = 0;j<tmp.size();i++,j++)
        {
    
    
            arr[i] = tmp[j];
        }
    }

binary search

A rather special divide-and-conquer algorithm
Binary search is actually a binary search. To use this search algorithm, it must be a sorted set, not out of order Code writing If found If the value of the mid subscript of the array is equal to the searched value, then the replacement will be performed and the mid will be returned. If it is found that the value of the mid subscript of the array is greater than the value found, let left = mid + 1 If it is found that the value of the mid subscript of the array is smaller than the searched value Just let right = mid - 1 left = 0, right = 6 (array length - 1), mid = left + (right - left) / 2 We want to find 15, then we first take three values
For example, there is an array of 1, 5, 6, 9, 10, 15, 17





Insert image description here

 int BinarySearch(int * arr,int len,int value)
    {
    
    
        int left = 0,right = len - 1,mid = -1;
        while (left < right)
        {
    
    
            mid = left + (right - left) << 1;
            if(arr[mid]==value){
    
    
                return mid;
            }

            if(arr[mid] > value){
    
    
                right = mid - 1;
            }else if(arr[mid] < value)
            {
    
    
                left = mid + 1;
            }
        }
        return -1;
    }

Guess you like

Origin blog.csdn.net/qq_41094072/article/details/134161723