another codelab sorting exercise I am having problem with.

any advice is appreciated.

You are given an array x of int elements along with an int variable n that contains the number of elements in the array. There are no duplicates in this array. You are also given an int variable m that has been declared. Assign to m the median value of the array.
NOTE: The median of a set of numbers is the number in the set such that there are as many numbers above that value as there are below. If the set has an even number of members, the median is the average of the pair of numbers such that there are as many numbers above the pair as there are below.
EXAMPLE 1: Given 5 8 1 9 7 the median is 7 because there are two numbers below (1 5) and two numbers above (8 9).
EXAMPLE 2: Given 3 7 1 4 6 9 the median is the average of 4 and 6 because there are two numbers above 4 and 6 (7 9) and two numbers below (3 1).

here is what i came up with:

for (int i=0; i<n; i++) {
    int small=i;
    for (int j=i+1; j<n; j++) {
        if (x[j]<x[small])
    int s=x[small];
if (n%2==0) 
4 Years
Discussion Span
Last Post by marnun

codeLab gives "Logical error" saying that value of m is incorrect.

this is test case table:
for n=6 and x={1, 2, 3, 4, 8, 9} m=6 (instead of 3)
for n=4 and x={2, 4, 6, 8} m=7 (instead of 5)


It's actually like this:
having n as 6 for example, divided by 2 is 3. In C++ the array notation starts from 0, so if you want to access the 3rd element, you actually access the 4th:

array: 1, 2, 3, 4, 8, 9
index: 0  1  2  3  4  5
size is 6 -> /2=3;
3rd element is 4 not 3, which is to expect.

What to do than? Simple, just modify the code where you calculate the median for the even numbers:

if ((n&1)==0)

Edited by Lucaci Andrew

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.