Created
June 26, 2014 20:49
-
-
Save gabhi/510e1c361363ae3d12cd to your computer and use it in GitHub Desktop.
Kth Largest element in array - java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class KthLargest { | |
public static int findKLargest(int[] ar, int low, int high, int k) { | |
int pivotIndex = partition(ar, low, high); | |
if (pivotIndex == k) { | |
return ar[pivotIndex]; | |
} | |
else if (pivotIndex > k) { | |
return findKLargest(ar, low, pivotIndex - 1, k); | |
} | |
else { | |
return findKLargest(ar, pivotIndex + 1, high, k); | |
} | |
} | |
private static int partition(int[] ar, int low, int high) { | |
int pivot = ar[low]; // first element as pivot | |
int i = low + 1; | |
for (int j = low + 1; j <= high; j++) { | |
if (ar[j] < pivot) { | |
swap(ar, i, j); | |
i++; | |
} | |
} | |
swap(ar, low, i - 1); | |
return i - 1; | |
} | |
private static void swap(int[] ar, int i, int j) { | |
int temp = ar[i]; | |
ar[i] = ar[j]; | |
ar[j] = temp; | |
} | |
public static void main(String[] args) { | |
int inputArray[] = { 5, 4, 3, 2, 1 }; | |
int k = 3; // K is from [1...n] | |
if (k > inputArray.length) | |
System.out.println("K can not be larger than size of the array"); | |
else { | |
int kLargest = findKLargest(inputArray, 0, inputArray.length - 1, k - 1); | |
System.out.println(kLargest); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment