SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arrays
Exercise:
Exercises
Question:8 | ISBN:9780136091813 | Edition: 2

Question

Write a method called median that accepts an array of integers as its parameter and returns the median of the numbers in the array. The median is the number that appears in the middle of the list if you arrange the elements in order. Assume that the array is of odd size (so that one sole element constitutes the median) and that the numbers in the array are between 0 and 99 inclusive. For example, the median of {5, 2, 4, 17, 55, 4, 3, 26, 18, 2, 17} is 5 and the median of {42, 37, 1, 97, 1, 2, 7, 42, 3, 25, 89, 15, 10, 29, 27} is 25. (Hint: You may wish to look at the Tally program from earlier in this chapter for ideas.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of median method:

	public static int median(int[] a)
	{
		for(int i = 0; i < a.length - 1; i++)
		{
			int minPos = i;
			for(int j = i + 1; j < a.length; j++)
			{
				if(a[j] < a[minPos])
					minPos = j;
			}

			if(i != minPos)
			{
				int temp = a[minPos];
				a[minPos] = a[i];
				a[i] = temp;
			}
		}

		return a[a.length / 2];
	}
0 0

Discussions

Post the discussion to improve the above solution.