Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Divide and Conquer Algorithms

Divide and Conquer Algorithms

Divide and conquer (English: Divide and conquer) is a very important algorithm paradigm based on multi-branch recursion. Literally interpreted as "divide and rule," it means splitting a complex problem into two or more identical or similar subproblems until the subproblems can be solved simply and directly; the solution to the original problem is then the combination of the solutions of the subproblems.

Simply put, divide and conquer consists of three steps:Divide -> Conquer -> Combine。

Imagine you have a big pile of building blocks in front of you that need to be sorted by color. If you start directly, you might feel overwhelmed. A smarter approach is: first split the pile into two smaller piles, then sort each smaller pile separately, and finally combine the two sorted piles. This "divide and rule" process is the core idea of the divide-and-conquer algorithm.

Divide and Conquer AlgorithmsIt is like the way a smart team leader solves a big problem:

  1. Divide: break the big problem into several smaller problems of the same type
  2. Conquer: recursively solve these small problems
  3. Combine: combine the solutions of the small problems into the solution of the original problem

Real-world examples:

Problem characteristics Other methods Divide-and-conquer approach
Large-scale data may be inefficient parallel processing after division
Complex structures difficult to solve directly simplify subproblems
recursively definable requires complex logic naturally suited to recursion
Independent subproblems difficult to parallelize perfectly supports parallelism

Core ideas and steps

Divide-and-conquer algorithms usually follow a clear three-step framework, which we can understand intuitively through the flowchart below:

Explanation of the figure above: The algorithm first determines whether the current problem is simple enough to be solved directly. If so, it solves it directly and returns the result; if not, it decomposes it into several subproblems, recursively solves each subproblem, and finally combines the results of the subproblems to obtain the final answer.

Specifically, these three steps are:

  1. Decomposition: decompose the original problem into several smaller, mutually independent subproblems of the same form as the original problem.
  2. Solution: recursively solve each subproblem. If a subproblem is small enough, solve it directly.
  3. Collapse: combine the solutions of the subproblems to form the solution to the original problem.

Classic applications of divide and conquer

To help you better understand how divide-and-conquer algorithms work, let's look at two of the most classic examples.

Application 1: Merge sort

Merge sort is a perfect embodiment of the divide-and-conquer idea; its goal is tosort an unordered array into an ordered array。

Algorithm steps:

  1. Decomposition: split the current array at the middle into left and right subarrays.
  2. Solution: recursively apply merge sort to the left and right subarrays.
  3. Collapse: merge the two sorted subarrays into a new ordered array.

Code example:

Example

def

merge_sort

(

arr

)

:

   

"""
    Merge sort main function
    :param arr: the list to be sorted
    :return: the new sorted list
    """

   

1. Conquer: if the array length is 0 or 1, return directly (base case)

   

if

len

(

arr

)

<=

1

:

       

return

arr

   

   

2. Divide: find the midpoint and split the array

    mid

=

len

(

arr

)

//

2

    left_half

=

arr

[

:mid

]

 

left subarray

    right_half

=

arr

[

mid:

]

 

right subarray

   

   

3. Conquer: recursively sort the left and right subarrays

    left_sorted

=

merge_sort

(

left_half

)

    right_sorted

=

merge_sort

(

right_half

)

   

   

4. Combine: merge the two ordered arrays

   

return

merge

(

left_sorted

,

right_sorted

)

def

merge

(

left

,

right

)

:

   

"""
    Merge two ordered lists
    :param left: ordered list A
    :param right: ordered list B
    :return: the merged ordered list
    """

    merged

=

[

]

 

List used to store the merge result

    i

=

j

=

0

   

i and j are pointers to left and right respectively

   

   

Compare the heads of the two lists and put the smaller element into merged

   

while

i

<

len

(

left

)

and

j

<

len

(

right

)

:

       

if

left

[

i

]

<=

right

[

j

]

:

            merged.

append

(

left

[

i

]

)

            i +

=

1

       

else

:

            merged.

append

(

right

[

j

]

)

            j +

=

1

   

   

Append the remaining elements (if any) directly to the end of merged

   

Since left and right are already ordered, the remaining part is also ordered

    merged.

extend

(

left

[

i:

]

)

    merged.

extend

(

right

[

j:

]

)

   

   

return

merged

Test Data

test_array

=

[

38

,

27

,

43

,

3

,

9

,

82

,

10

]

print

(

"Original array:"

,

test_array

)

sorted_array

=

merge_sort

(

test_array

)

print

(

"Sorted array:"

,

sorted_array

)

Output: Original array: [38, 27, 43, 3, 9, 82, 10]

Output: Sorted array: [3, 9, 10, 27, 38, 43, 82]

Application 2: Binary search

Binary search is used toa sorted arrayto quickly locate a target value. It continuously halves the search range, a simplified version of the divide-and-conquer strategy (usually handling only one subproblem with no need to combine).

Algorithm steps:

  1. Decomposition: Find the middle element of the array.
  2. Solution:
  3. If the middle element equals the target value, the search succeeds.
  4. If the target is smaller than the middle element, recursively search the left half.
  5. If the target is larger than the middle element, recursively search the right half.
  6. - If the middle element equals the target value, the search succeeds. - If the target is smaller than the middle element, recursively search the left half. - If the target is larger than the middle element, recursively search the right half.
    1. Collapse: Binary search usually needs no combine step, because once the target is found, its position can be returned directly.

    Code example:

    Example

    def

    binary_search

    (

    arr

    ,

    target

    ,

    low

    ,

    high

    )

    :

       

    """
        Binary search (recursive version)
        :param arr: the sorted list
        :param target: the target value to find
        :param low: the starting index of the current search range
        :param high: the ending index of the current search range
        :return: the index of the target value, or -1 if not found
        """

       

    Base case: invalid search range, meaning the target was not found

       

    if

    low

    high:

           

    return

    1

       

       

    Divide: compute the middle index

        mid

    =

    (

    low + high

    )

    //

    2

       

       

    Conquer: judge and recurse

       

    if

    arr

    [

    mid

    ]

    ==

    target:

           

    return

    mid  

    Target found, return the index

       

    elif

    target

    <
    
    arr
    
    [
    
    mid
    
    ]

    :

           

    Target is in the left half, recursively search the left half

           

    return

    binary_search

    (

    arr

    ,

    target

    ,

    low

    ,

    mid -

    1

    )

       

    else

    :

           

    Target is in the right half, recursively search the right half

           

    return

    binary_search

    (

    arr

    ,

    target

    ,

    mid +

    1

    ,

    high

    )

    Test data (must be sorted!)

    sorted_list

    =

    [

    2

    ,

    5

    ,

    8

    ,

    12

    ,

    16

    ,

    23

    ,

    38

    ,

    56

    ,

    72

    ,

    91

    ]

    target_value

    =

    23

    result

    =

    binary_search

    (

    sorted_list

    ,

    target_value

    ,

    0

    ,

    len

    (

    sorted_list

    )

    1

    )

    if

    result

    !=

    1

    :

       

    print

    (

    f

    "The index of target value {target_value} in the array is: {result}"

    )

    else

    :

       

    print

    (

    f

    "Target value {target_value} is not in the array."

    )

    Output: The index of target value 23 in the array is: 5


    Characteristics and complexity analysis of divide-and-conquer algorithms

    Algorithm characteristics

    Feature Description
    Problem can be decomposed The original problem must be decomposable into smaller similar subproblems.
    Subproblems are independent Subproblems should preferably be mutually independent, making solving and combining simpler.
    Has a termination condition There must be a simple base case that can be solved directly when the problem is small enough.
    Solutions can be combined It must be possible to effectively combine the solutions of the subproblems into the solution of the original problem.

    Time complexity analysis

    The time complexity of divide-and-conquer algorithms can usually be analyzed with the master theorem , whose recurrence generally has the form: $$ T(n) = aT(\frac{n}{b}) + f(n) $$ where:

    For example, for merge sort:


    Practical Exercise

    Now it's time to consolidate your understanding of divide-and-conquer algorithms through practice. Please try the following exercises:

    Exercise 1: Implement quicksort Quicksort is another classic divide-and-conquer algorithm. Its idea is:

    1. Decomposition: Choose a "pivot" element and rearrange the array so that all elements smaller than the pivot go to the left and all larger ones go to the right (partition operation).
    2. Solution: recursively apply quicksort to the subarrays on the left and right of the pivot.
    3. Collapse: no explicit combine is needed, because after partitioning the array is already partially ordered.

    Your task: Based on the description above, try writing Python code for quicksort.

    Exercise 2: Find the maximum subarray sum in an array Problem: Given an integer array (which may contain negative numbers), find a contiguous subarray with the maximum sum. For example, for [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum subarray is [4, -1, 2, 1], whose sum is 6。

    Hint (divide-and-conquer approach):

    1. Split the array at the middle into left and right halves.
    2. The maximum subarray sum may appear in:the left half、the right half, orcrossing the midpoint。
    3. Recursively solve for the maximum subarray sum in the left and right halves.
    4. Compute the maximum subarray sum crossing the midpoint (need to accumulate leftward and rightward from the midpoint to find the maximum).
    5. Return the maximum of the three.

    Try to solve this problem using the divide-and-conquer strategy.