Open In App

Divide and Conquer in Python

Last Updated : 06 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Divide and Conquer is an effective approach for managing challenges that divides a major problem into smaller, easier-to-manage subproblems. The solution to the main problem is obtained by combining the final solutions from multiple individually solved subproblems. This approach works especially well with issues that naturally break down into different elements.

Divide and Conquer strategy typically involves three key steps:

  • Divide: The first step is to divide the primary problem into smaller subissues. A key characteristic of this approach is its recursive nature, which allows each subproblem to be further divided down into smaller subproblems until it reaches a base case that is easy to solve.
  • Conquer: Each subproblem is tackled separately as soon as it is small enough. Recursive use of the divide-and-conquer approach or a brute-force approach can be utilized to do this.
  • Merge: To solve the primary problem, the subproblems' answers must be merged in the last stage. It is up to the particular problem being solved and how this combination is applied.

Divide and Conquer Example:

Merge Sort:

One well-known example of a divide-and-conquer algorithm is merge sort. An overview of its general operation for sorting a list of numbers is provided here:

  • Divide: Return the list itself since it has already been sorted if there is only one element in the list. If not, split the list in half, making them roughly equal in size.
  • Conquer: Use merge sort to recursively sort the two parts.
  • Merge: Reassemble the two sorted lists into a single one. Comparing the elements from either half and inserting the smaller element to the final sorted list is the procedure of merging. Until all of the elements are combined, this process keeps going.

Implementation of Merge Sort using Divide and Conquer in Python:

Below is the implementation of Merge Sort in Python using Divide and Conquer Algorithm:

Python
# Function to merge two sorted arrays
def merge(arr1, arr2):
    i = 0
    j = 0
    # Array to store the merged sorted array
    result = []
    while(i < len(arr1) and j < len(arr2)):
        # If arr1[i] is smaller than arr2[j], push arr1[i] into the result and move to the next element in arr1
        if arr2[j] > arr1[i]:
            result.append(arr1[i])
            i += 1
        # If arr2[j] is smaller than arr1[i], push arr2[j] into the result and move to the next element in arr2
        else:
            result.append(arr2[j])
            j += 1

    # Push the remaining elements of arr1, if any
    while(i < len(arr1)):
        result.append(arr1[i])
        i += 1
        # Push the remaining elements of arr2, if any
    while(j < len(arr2)):
        result.append(arr2[j])
        j += 1

    return result


# Function to sort arr using merge sort
def mergeSort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr)//2
    # Sort the left half
    left = mergeSort(arr[:mid])
    # Sort the right half
    right = mergeSort(arr[mid:])

    return merge(left, right)


# Driver Code
if __name__ == '__main__':
    arr = [12, 11, 13, 5, 6, 7]
    print("Given array is")
    print(*arr)
    arr = mergeSort(arr)
    print("\nSorted array is ")
    print(*arr)

Output
[1, 2, 3, 4, 5, 6, 7, 8]

Time Complexity: O(N*logN), where N is the size of input array arr[].
Auxiliary Space: O(N)


Next Article
Article Tags :

Similar Reads