Tuesday, 26 July 2016

Maximum and minimum of an array using minimum number of comparisons

Write a C function to return minimum and maximum in an array. You program should make minimum number of comparisons. 

Idea : Using tournament algorithm




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
using namespace std;

struct minMaxPair{
    int maxi;
    int mini;
};

struct minMaxPair minMaxTournament(int *arr, int low, int high){
    //Number of elements is one
    if(low == high){
        struct minMaxPair maxmin;
        maxmin.maxi = arr[low];
        maxmin.mini = arr[low];
        return maxmin;
    } //Number of elements is two
    else if(low == high - 1){
        struct minMaxPair maxmin;
        if(arr[low] < arr[high]){
            maxmin.mini = arr[low];
            maxmin.maxi = arr[high];
        } else{
            maxmin.maxi = arr[low];
            maxmin.mini = arr[high];
        }
        return maxmin;
    } //Number of elements is more than two
    else{
        int mid = (low + high) / 2;
        struct minMaxPair left, right, result;
        left = minMaxTournament(arr, 0, mid);
        right = minMaxTournament(arr, mid + 1, high);
        if(left.mini <= right.mini){
            result.mini = left.mini;
        } else {
            result.mini = right.mini;
        }
        if(left.maxi >= right.maxi){
            result.maxi = left.maxi;
        } else {
            result.maxi = right.maxi;
        }
        return result;
    }
}

int main(){
    int arr[] = {1000, 11, 445, 1, 330, 3000};
    int n = sizeof(arr) / sizeof(arr[0]);
    struct minMaxPair result = minMaxTournament(arr, 0, n - 1);
    cout << "Maximum : " << result.maxi << endl;
    cout << "Minimum : " << result.mini << endl;
    return 0;
}
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive