Saturday, December 5, 2020

Introduction to Programming in C Slot 1: Question 1 Solution

 

Slot 1: Question 1

Due on 2020-12-05, 11:00 IST
You are given a sequence of positive integers, terminating in a
-1. (The -1 is not part of the sequence, it is used to denote the end
of the input.) There are at most 100 integers in the sequence.

An inversion is a pair of integers (i,j) such that i occurs before j
in the sequence, but i > j.

You have to output the number of inversions in the input sequence.


Sample Input 1
-------------
1 3 2 -1


Sample Output 1
--------------
1

Explanation for Sample 1
------------------------
The pairs of integers in the sequence are (1,3), (1,2) and
(3,2). Among these, (3,2) is the only inversion.


Sample Input 2
---------------
20 20 5 4 -1

Sample Output 2
----------------
5

Explanation for Sample 2
------------------------
The pairs of integers are (20,20), (20,5), (20,4), (20,5), (20,4) and
(5,4). All except (20,20) are inversions.
Your last recorded submission was on 2020-12-05, 10:13 IST
Select the Language for this assignment. 
1
#include<stdio.h>
2
3
void main(){
4
5
int nums[100];
6
int result =0;
7
int temp,index=0,i,j;
8
9
  scanf("%d",&temp);
10
11
  while(temp != -1){
12
  nums[index++] = temp;
13
  scanf("%d",&temp);
14
  }
15
  
16
  for (i = 0; i < index - 1; i++) 
17
       for ( j = i + 1; j < index; j++) 
18
            if (nums[i] > nums[j]) 
19
                result++;
20
21
printf("%d",result);
22
23
}

No comments:

Post a Comment