Count of pairs (x, y) in an array such that x < y in C++

C++Server Side ProgrammingProgramming

We are given an integer array and the task is to count the total number of pairs (x, y) that can be formed using the given array values such that the integer value of x is less than y.

Input − int arr[] = { 2, 4, 3, 1 }

Output − Count of pairs (x, y) in an array such that x < y are − 6

Explanation

XYX < Y
24true
23true
21false
43false
41false
42false
32false
12true
34true
14true
31false
13false

Approach used in the below program is as follows

  • Input an array of integer elements to form an pair

  • Calculate the size of an array pass the data to the function for further processing

  • Create a temporary variable count to store the pairs having x less than y

  • Start loop FOR from i to 0 till the size of an array

  • Inside the loop, start another loop FOR from j to 0 till the size of an array

  • Inside the loop, check IF arr[i] < arr[j] == TRUE then increment the count by 1

  • Return the count

  • Print the result

Example

 Live Demo

#include <iostream>
using namespace std;
int X_Less_Y(int arr[],int size){
   int count = 0;
   for (int i = 0; i < size; i++){
      for (int j = 0; j < size; j++){
         if (arr[i] < arr[j]){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int arr[] = { 2, 4, 3, 1 };
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs (x, y) in an array such that x < y are: "<<X_Less_Y(arr, size);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of pairs (x, y) in an array such that x < y are: 6
raja
Published on 31-Aug-2020 14:51:17
Advertisements