mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
Add another method to find kth number (#5918)
This commit is contained in:
committed by
GitHub
parent
871e4df0d9
commit
95875b0ae4
@@ -14,21 +14,30 @@ public class FindKthNumberTest {
|
||||
assertEquals(3, FindKthNumber.findKthMax(array1, 3));
|
||||
assertEquals(4, FindKthNumber.findKthMax(array1, 2));
|
||||
assertEquals(5, FindKthNumber.findKthMax(array1, 1));
|
||||
assertEquals(3, FindKthNumber.findKthMaxUsingHeap(array1, 3));
|
||||
assertEquals(4, FindKthNumber.findKthMaxUsingHeap(array1, 2));
|
||||
assertEquals(5, FindKthNumber.findKthMaxUsingHeap(array1, 1));
|
||||
|
||||
int[] array2 = {7, 5, 8, 2, 1, 6};
|
||||
assertEquals(5, FindKthNumber.findKthMax(array2, 4));
|
||||
assertEquals(6, FindKthNumber.findKthMax(array2, 3));
|
||||
assertEquals(8, FindKthNumber.findKthMax(array2, 1));
|
||||
assertEquals(5, FindKthNumber.findKthMaxUsingHeap(array2, 4));
|
||||
assertEquals(6, FindKthNumber.findKthMaxUsingHeap(array2, 3));
|
||||
assertEquals(8, FindKthNumber.findKthMaxUsingHeap(array2, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFindKthMaxEdgeCases() {
|
||||
int[] array1 = {1};
|
||||
assertEquals(1, FindKthNumber.findKthMax(array1, 1));
|
||||
assertEquals(1, FindKthNumber.findKthMaxUsingHeap(array1, 1));
|
||||
|
||||
int[] array2 = {5, 3};
|
||||
assertEquals(5, FindKthNumber.findKthMax(array2, 1));
|
||||
assertEquals(3, FindKthNumber.findKthMax(array2, 2));
|
||||
assertEquals(5, FindKthNumber.findKthMaxUsingHeap(array2, 1));
|
||||
assertEquals(3, FindKthNumber.findKthMaxUsingHeap(array2, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -36,6 +45,8 @@ public class FindKthNumberTest {
|
||||
int[] array = {1, 2, 3, 4, 5};
|
||||
assertThrows(IllegalArgumentException.class, () -> FindKthNumber.findKthMax(array, 0));
|
||||
assertThrows(IllegalArgumentException.class, () -> FindKthNumber.findKthMax(array, 6));
|
||||
assertThrows(IllegalArgumentException.class, () -> FindKthNumber.findKthMaxUsingHeap(array, 0));
|
||||
assertThrows(IllegalArgumentException.class, () -> FindKthNumber.findKthMaxUsingHeap(array, 6));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -43,8 +54,10 @@ public class FindKthNumberTest {
|
||||
int[] array = generateArray(1000);
|
||||
int k = new Random().nextInt(1, array.length);
|
||||
int result = FindKthNumber.findKthMax(array, k);
|
||||
int maxK = FindKthNumber.findKthMaxUsingHeap(array, k);
|
||||
Arrays.sort(array);
|
||||
assertEquals(array[array.length - k], result);
|
||||
assertEquals(array[array.length - k], maxK);
|
||||
}
|
||||
|
||||
public static int[] generateArray(int capacity) {
|
||||
|
||||
Reference in New Issue
Block a user