Advertisement
coffeebeforecode

CSE2012 PP1 Q2

Aug 12th, 2021
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | None | 0 0
  1. /*
  2. Counting inversions
  3. Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array
  4. is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count
  5. is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j]
  6. and i < j.
  7. Example: Input: arr[] = {8, 4, 2, 1}
  8. Output: 6. The six inversions: (8,4), (4,2), (8,2), (8,1), (4,1), (2,1).
  9. Input: arr[] = {3, 1, 2}
  10. Output: 2. The two inversions: (3,1), (3,2).
  11. */
  12.  
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15.  
  16. void solve(){
  17.     unsigned int size;
  18.     int *arr;
  19.     int i, j;
  20.     // Input
  21.     printf("Enter size of array: ");
  22.     scanf("%u", &size);
  23.     arr = (int *)malloc(sizeof(int)*size);
  24.    
  25.     printf("\nInput values: ");
  26.     for(i = 0; i < size; i++){
  27.         scanf("%d", &arr[i]);
  28.     }
  29.  
  30.     //solving
  31.     unsigned int inversions = 0;
  32.  
  33.     for (i = 0; i < size-1; i++){
  34.         for(j = i+1; j < size; j++){
  35.             if (arr[i] > arr[j]){
  36.                 inversions++;
  37.             }
  38.         }
  39.     }
  40.  
  41.     printf("\nThe inversion count is %d\n", inversions);
  42. }
  43.  
  44. int main(){
  45.     solve();
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement