Priority Queue
orders elements according to their natural order, or as per Comparator
if provided at queue creation time. The default Priority Queue
is implemented using Min-Heap
, that is, the top element of the heap will be the minimum one in the heap. A Priority Queue
does not allow null elements. it relies on the natural ordering of elements hence also does not allow non-comparable objects.
package org.wesome.dsalgo;
import java.util.PriorityQueue;
public class NthLargest {
public static int findNthLargest(int[] list, int nThElement) {
if (1 > nThElement) {
System.out.println("minimum nTh element should be 1, provided " + nThElement);
return -1;
}
if (list.length < nThElement) {
System.out.println("list is empty or elements are less then " + nThElement);
return -1;
}
/* insert all the elements in PriorityQueue up to nth index */
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < nThElement; i++) {
pq.add(list[i]);
}
/* loop from nth position to end of array */
for (int i = nThElement; i < list.length; i++) {
/* check top of PriorityQueue, if it's more than current element of array then pop the top and insert the current element */
if (list[i] > pq.peek()) {
pq.poll();
pq.add(list[i]);
}
}
return pq.peek();
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.wesome.dsalgo.NthLargest.findNthLargest;
public class FindNthLargestTest {
@Test
void FindNthLargestTest1() {
int nThElement = 3;
int[] arr = new int[]{1, 2, 3, 4, 5};
Assertions.assertEquals(3, findNthLargest(arr, nThElement));
}
@Test
void FindNthLargestTest2() {
int nThElement = 3;
int[] arr = new int[]{10, 9, 8, 7, 6};
Assertions.assertEquals(8, findNthLargest(arr, nThElement));
}
@Test
void FindNthLargestTest3() {
int nThElement = 10;
int[] arr = new int[]{8, 9, 0, 1, 2, 3};
Assertions.assertEquals(-1, findNthLargest(arr, nThElement));
}
@Test
void FindNthLargestTest4() {
int nThElement = 0;
int[] arr = new int[]{10, 9, 8, 7, 6};
Assertions.assertEquals(-1, findNthLargest(arr, nThElement));
}
@Test
void FindNthLargestTest5() {
int nThElement = -1;
int[] arr = new int[]{10, 9, 8, 7, 6};
Assertions.assertEquals(-1, findNthLargest(arr, nThElement));
}
@Test
void FindNthLargestTest6() {
int nThElement = 5;
int[] arr = new int[]{10, 9, 8, 7, 6};
Assertions.assertEquals(6, findNthLargest(arr, nThElement));
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.2.0"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}