• Java script returning wrong value
    2 replies, posted
Hello gentlemen! can any of you guys help me understand why this script is returning 100 instead of the median? [CODE] package eksamen; public class Kap7opg7 { public static void main (String[] args){ //int []b = new int[1000]; //int x; //for (x = 0; x < b.length; x++){ // b[x] = x; //} int []b = {1,4,6,8,12,15,18,22,26,34,53,62,77,89,92,94,100}; System.out.println(median(b)); } static int median (int[] a){ int ca = 0; int med1 = (a[a.length/2]); int med2 = (a[(a.length/2)+1]); int medsum = ((med1 + med2) / 2); int j; do{ for (j = 0; j < a.length; j++){ if (a[j] >= medsum){ ca = a[j]; } } }while (ca < medsum); return ca; } } [/CODE]
As you're assuming that the array is sorted you should grab the median without a loop. Other than that, you have two loops, the inner of which always runs for all elements and will overwrite [I]ca[/I] with all elements larger than medsum, the last of which is 100. The correct solution would be to check whether the length of a is even, then if it is to grab the values at a.length/2 and a.length/2-1 and return the average. If it isn't the value at a.length/2 (truncated) should be the correct one. (Assuming JS has 0-based arrays.) Maybe there's a way to avoid branching by taking advantage of integer division, but I don't know that off the top of my head right now. Maths references usually assume an index of 1 for the first element, so you have to take an offset of 1 into account when accessing the array.
First of all, indent your code, if you don't you are just making it harder for yourself. The first 4 lines of the function pretty much got you there. I have literally no clue what you where trying to do in the last 10 lines. [cpp]static int median(int[] a) { if(a.length % 2 == 0) // Is the length even? return (a[(a.length - 1)/2] + a[(a.length - 1) / 2 -1]) / 2 // Return the mean else return a[a.length - 1)/2 ] // Return the median } [/cpp] Edit: RTFM
Sorry, you need to Log In to post a reply to this thread.