Objective In this challenge, we practice calculating  quartiles . Check out the  Tutorial  tab for learning materials and an instructional...

Day 1: Quartiles Solution

 Objective

In this challenge, we practice calculating quartiles. Check out the Tutorial tab for learning materials and an instructional video!

Task
Given an array, , of  integers, calculate the respective first quartile (), second quartile (), and third quartile (). It is guaranteed that , and  are integers.

Input Format

The first line contains an integer, , denoting the number of elements in the array.
The second line contains  space-separated integers describing the array's elements.

Constraints

  • , where  is the  element of the array.

Output Format

Print  lines of output in the following order:

  1. The first line should be the value of .
  2. The second line should be the value of .
  3. The third line should be the value of .

Sample Input

9
3 7 8 5 12 14 21 13 18

Sample Output

6
12
16

Explanation

. When we sort the elements in non-decreasing order, we get . It's easy to see that .

As there are an odd number of data points, we do not include the median (the central value in the ordered list) in either half:

Lower half (L): 3, 5, 7, 8

Upper half (U): 13, 14, 18, 21

Now, we find the quartiles:

  •  is the . So, .
  •  is the . So, .
  •  is the . So, .

Solution



import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int q1=0,q2=0,q3=0;
        int[] ar = new int[n];
        for(int i=0;i<n;i++)
            ar[i]=sc.nextInt();
        Arrays.sort(ar);
        if(n%2==1) {
            int mid = n/2;
            q1 = (ar[mid/2-1] + ar[mid/2])/2;
            q2 = ar[mid];
            q3 = (ar[((mid+n)/2)] + ar[((mid+n)/2 +1)]) /2;
            System.out.print(q1+"\n"+q2+"\n"+q3);
        
        } else {
            
            int mid = n/2;
            
            q2 = (ar[mid]+ar[mid-1])/2;
            
            if((n-mid-1)%2==0) {
                q1 = (ar[mid/2]);
                q3 = ar[((mid+n)/2)];
            } else {
                q1 = (ar[mid/2]);
                q3 = (ar[((mid+n)/2-1)]+ar[((mid+n)/2)])/2;
            }
            System.out.print(q1+"\n"+q2+"\n"+q3);
            
        }
        
        
    }
}

0 comments:

Do not spam here.