Divide and conquer, teach you how to solve the problem!

divide and conquer

What is divide and conquer?

In front of us, we have learned a series of data structures and related algorithms, including sorting and searching algorithms. The divide and conquer of this study is not a data structure, nor an algorithm, but a method in algorithm design, which can be understood as a kind of thought. We can use this idea to design many kinds of algorithms.

Divide and conquer is to divide a problem into multiple small problems similar to the original problem, solve the small problems recursively, and then combine the results to solve the original problem. It is mainly divided into three parts, namely "separation", "recursive solution", and "combination".

base case

scene one

merge sort

  • Divide: Divide the array into two from the middle
  • Solution: Merge and sort the two subarrays recursively
  • Combine: Merge sorted subarrays

First, it splits a large array into two small arrays, and then splits each small array into two small arrays, and so on. Finally, it merges and sorts all the small arrays of single elements, and finally forms a large array to solve the problem.

Merge sort is a typical application of the idea of ​​divide and conquer.

scene two

quick sort

  • Divide: select the benchmark, divide the array into two sub-arrays according to the benchmark
  • Solution: Quicksort the two subarrays recursively
  • Merge: Merge two subarrays

The steps are similar to merge sort.

scene three

Binary search also has the characteristics of "separation", "solution", and "combination".

Original Link: Vegetable Garden Front End

Guess you like

Origin blog.csdn.net/qq2603375880/article/details/131749372