Search
 
SCRIPT & CODE EXAMPLE
 

CPP

divide and conquer based algorithm to find maximum and minimum of an array

#include <iostream>
#include <climits>
using namespace std;
void findMinAndMax(int a[], int low, int high, int &min, int &max)
{
    if (low == high)              
    {
        if (max < a[low]) 
        {          
            max = a[low];
        }
 
        if (min > a[high]) 
        {        
            min = a[high];
        }
        return;
    }
    if (high - low == 1)               
    {
        if (a[low] < a[high])       
        {
            if (min > a[low]) 
            {      
                min = a[low];
            }
 
            if (max < a[high]) 
            {     
                max = a[high];
            }
        }
        else {
            if (min > a[high]) 
            {     
                min = a[high];
            }
 
            if (max < a[low]) 
            { 
                max = a[low];
            }
        }
        return;
    }
    int mid = (low + high) / 2;
    findMinAndMax(a, low, mid, min, max);
    findMinAndMax(a, mid + 1, high, min, max);
}
int main()
{
    int a[] = { 7, 2, 9, 3, 1, 6, 7, 8, 4 };
    int max = INT_MIN, min = INT_MAX;
 
    int n = 9;
    findMinAndMax(a, 0, n - 1, min, max);
 
    cout << "The minimum array element is " << min << endl;
    cout << "The maximum array element is " << max << endl;
 
    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: input in c++ 
Cpp :: how to get the size of a vector in c++ 
Cpp :: how to print in cpp 
Cpp :: how to get the type of a variable in c++ 
Cpp :: create a 2d vector in c++ 
Cpp :: how to get size of 2d vector in c++ 
Cpp :: c++ call by reference 
Cpp :: naive pattern matching algorithm 
Cpp :: indexing strings in c++ 
Cpp :: c++ cout format 
Cpp :: why is using namespace std a bad practice 
Cpp :: initialize vector of vector c++ 
Cpp :: how to initialize a vector of pairs in c++ 
Cpp :: c++ string to int 
Cpp :: stoi() c++ 
Cpp :: inline function in c++ 
Cpp :: factorial loop c++ 
Cpp :: pragma cpp 
Cpp :: how to find min of two numbers in c++ 
Cpp :: c++ print out workds 
Cpp :: power of a number 
Cpp :: how to get hcf of two number in c++ 
Cpp :: how to delete an element in vector pair in cpp 
Cpp :: vector library c++ 
Cpp :: SUMOFPROD2 solution 
Cpp :: map in c 
Cpp :: count sort algorithm 
Cpp :: c++ vector first element 
Cpp :: il2cpp stuck unity 
Cpp :: Exit Button c++ code 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =