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:7 | ISBN:9780136091813 | Edition: 2

Question

Write a method called kthLargest that accepts an integer k and an array a as its parameters and returns the element such that k elements have greater or equal value. If k = 0 , return the largest element; if k = 1 , return the second-largest element, and so on. For example, if the array passed contains the values {74, 85, 102, 99, 101, 56, 84} and the integer k passed is 2, your method should return 99 because there are two values at least as large as 99

(101 and 102). Assume that 0 ≤ k < a.length. (Hint: Consider sorting the array or a copy of the array first.)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of kthLargest method:

	public static int kthLargest(int[] a, int k)
	{
		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 - k - 1];
	}
0 0

Discussions

Post the discussion to improve the above solution.