Divide and conquer largest two elements

Divide and conquer largest two numbers problem

Given an array of integers. Find the first and second largest elements in the array. Use divide and conquer technique.

Divide and conquer algorithm largest two elements

Simply divide the array into two halves then find the largest two elements in each half. At the end you need to return the largest two out of the four because each half returns two elements. The base case for recursion is when the array contains one or two elements. In that case the largest two elements are the first and the second elements of the array.

Notice that this algorithm runs in linear time like the one and two loops solutions but the number of comparisons made is less.

Code

Here is a c++ code for divide and conquer first and second largest numbers using a single loop

Thanks for reading. Please use the comments section below for feedback.

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *