Mark As Completed Discussion

Single Loop Trick/Comparison in Pairs

In the Comparison in Pairs method, we'll implement the following steps.

  • If the size of the array is odd, then we'll initialize the minimum and maximum values to the first element of the array.
  • If the size is even, then we'll compare the first and second elements of the array and initialize minimum and maximum values accordingly.
  • Next, we'll traverse the array in pairs.
  • After that, we'll find the minimum and maximum value of each pair and then update the minimum and maximum value of the entire array accordingly.

Let's have a look at the Pseudocode:

Pseudocode

SNIPPET
1int[] findMinimumAndMaximum(int input[], int size)
2{
3    int maximum, minimum
4    int index
5    if ( size % 2 ==0)
6    {
7      if ( input[0] < input[1] )
8         {
9            maximum = input[1]
10            minimum = input[0]
11         }
12         else
13         {
14            maximum = input[0]
15            minimum = input[1]
16          }
17       index = 2   
18    }
19    else
20    {
21        maximum = input[0]
22        minimum = input[0]
23        index = 1      
24    }
25    while ( index < size )
26    {
27        if ( input[index] < input[index+1] )
28        {
29            if ( input[index] < minimum )
30                minimum = input[index]
31            if ( input[index+1] > maximum )
32                maximum = input[index+1]
33        }
34        else
35        {
36            if ( input[index] > maximum )
37                maximum = input[index]
38            if ( input[index+1] < minimum )
39                minimum = input[index+1] 
40        }
41        index = index + 2
42    }
43    
44    int result[2] = {maximum, minimum}
45   return result
46}

Next, we'll implement the above steps in Python, Javacript, and Java:

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment