Skip to content

Commit

Permalink
kth largest element in unsorted array LC215
Browse files Browse the repository at this point in the history
  • Loading branch information
ankurjuneja committed Jan 31, 2021
1 parent 238252a commit 2f9c7d7
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
4 changes: 3 additions & 1 deletion ArraysAndStrings/Tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,4 +260,6 @@ void printTwoSum(int[] array, int k)
}
}
}
```
```

**[Kth Largest in an array](https://github.com/ankurjuneja/React-Java-Concepts/blob/master/src/ArraysAndStrings/Kthlargest.java)**
57 changes: 57 additions & 0 deletions src/ArraysAndStrings/Kthlargest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package ArraysAndStrings;

public class Kthlargest
{
public static int findKthLargest(int[] nums, int k)
{
if (null == nums || nums.length == 0)
{
return Integer.MIN_VALUE;
}

return qSort(nums, 0, nums.length-1, k);
}

private static int qSort(int[] nums, int left, int right, int k)
{
if (nums[left] >= nums[right])
{
return nums[right];
}

int i = left;
for (int j = left + 1; j <= right; j++)
{
if (nums[j] > nums[i]) {
i++;
swap(nums, i, j);
}
}
swap(nums, i, left);

if (k == i + 1)
{
return nums[i];
}
else if (k > i + 1)
{
return qSort(nums, i+1, right, k);
}
else
{
return qSort(nums, left, i-1, k);
}
}

private static void swap(int[] nums, int i, int j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}

public static void main(String[] args)
{
int secondlargest = findKthLargest(new int[]{3,2,5,1,6,4}, 2);
}
}

0 comments on commit 2f9c7d7

Please sign in to comment.