Friday, August 17, 2018

INVERSION COUNT USING FUNCTION

  • Problem Description

    Write a program to find the ARRAY Inversion array.

    Inversion Count for an array indicates how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.

    Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j

    Example 1:
    The sequence 2, 4, 1, 3, 5 has 3 inversions (2, 1), (4, 1), (4, 3).

    Example 2:
    The sequence 1, 2, 3, 4, 5 has 0 inversion count, because the array is in sorted order

    Example 3:
    The sequence 4, 3, 2, 1 has 6 inversion count (4, 3), (4, 2), (4, 1), (3, 2), (3,1), (2,1)

    Example 4:
    The sequence 3, 1, 2 has 2 inversion count (3, 1), (3, 2)

    Input and Output Format:

    Input consists of n+1 integers where n corresponds to the number of elements in the array.

    The first integer corresponds to n and the next n integers correspond to the elements in the array.

    Output consists of a single integer which corresponds to the number of inversions in an array.

    Assume that the maximum number of elements in the array is 20.

    Refer sample input and output for formatting specifications.

    All text in bold corresponds to input and the rest corresponds to output.
  • CODING ARENA::
  • #include <stdio.h>
    int main()
    {
      int a,i,j,c=0;
      scanf("%d",&a);
      int arr[a];
      for(i=0;i<a;i++)
      {
        scanf("%d",&arr[i]);
      }
      for(i=0;i<a;i++)
      {
        for(j=i;j<a;j++)
        {
          if(arr[i]>arr[j])
          {
            c++;
          }
        }
      }
      printf("%d",c);
      

    return 0;
    }
  • Test Case 1

    Input (stdin)
    5
    
    2 4 1 3 5
    
    
    Expected Output
    3
  • Test Case 2

    Input (stdin)
    5
    
    1 2 3 4 5
    
    
    Expected Output
    0

No comments:

Post a Comment