Skip to content

Commit d45fb53

Browse files
committed
Add priorityqueue code
1 parent d98f33f commit d45fb53

File tree

2 files changed

+119
-0
lines changed

2 files changed

+119
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package datastructure.priorityqueue;
2+
3+
import org.junit.Test;
4+
5+
import java.util.PriorityQueue;
6+
import java.util.Queue;
7+
8+
import static org.hamcrest.CoreMatchers.is;
9+
import static org.junit.Assert.assertThat;
10+
11+
public class CalcTopTen {
12+
13+
/*
14+
TASK
15+
많은 수 중 top 10을 구한다.
16+
*/
17+
18+
@Test
19+
public void test() {
20+
TopTen t = new TopTen();
21+
t.put(1);
22+
t.put(2);
23+
t.put(3);
24+
t.put(4);
25+
t.put(5);
26+
t.put(6);
27+
t.put(7);
28+
t.put(8);
29+
t.put(9);
30+
t.put(10);
31+
t.put(11);
32+
t.put(12);
33+
t.put(19);
34+
t.put(21);
35+
t.put(13);
36+
int[] arr = new int[10];
37+
int j = 0;
38+
for (int i = arr.length; i > 0; i--) {
39+
arr[j] = i;
40+
j++;
41+
}
42+
assertThat(t.getTop10(), is(arr));
43+
}
44+
45+
public class TopTen {
46+
private Queue<Integer> queue = new PriorityQueue<>();
47+
48+
private void put(int data) {
49+
queue.add(data);
50+
}
51+
52+
private int[] getTop10() {
53+
int[] arr = new int[10];
54+
for (int i = arr.length - 1; i >= 0; i--) {
55+
arr[i] = queue.poll();
56+
}
57+
return arr;
58+
}
59+
60+
private void read(int n) {
61+
if (queue.size() < 10) {
62+
queue.offer(n);
63+
} else {
64+
int tenth = queue.peek();
65+
if (n > tenth) {
66+
queue.poll();
67+
queue.offer(n);
68+
}
69+
}
70+
}
71+
}
72+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package datastructure.priorityqueue;
2+
3+
import org.junit.Test;
4+
5+
import java.util.PriorityQueue;
6+
import java.util.Queue;
7+
8+
import static org.hamcrest.CoreMatchers.is;
9+
import static org.junit.Assert.assertThat;
10+
11+
public class HeapSortByUsingPQ {
12+
13+
/*
14+
TASK
15+
Priority queue를 사용하여 heap sort를 하라.
16+
*/
17+
18+
@Test
19+
public void test() {
20+
int[] arr = new int[5];
21+
arr[0] = 3;
22+
arr[1] = 7;
23+
arr[2] = 1;
24+
arr[3] = 9;
25+
arr[4] = 6;
26+
27+
int[] sortedArr = new int[5];
28+
sortedArr[0] = 1;
29+
sortedArr[1] = 3;
30+
sortedArr[2] = 6;
31+
sortedArr[3] = 7;
32+
sortedArr[4] = 9;
33+
assertThat(heapSort(arr), is(sortedArr));
34+
}
35+
36+
public int[] heapSort(int[] arr) {
37+
Queue<Integer> queue = new PriorityQueue<>();
38+
for (int i = 0; i < arr.length; i++) { //O(nlogn)
39+
queue.add(arr[i]);
40+
}
41+
int[] newArr = new int[arr.length];
42+
for (int i = 0; i < newArr.length; i++) { //O(nlogn)
43+
newArr[i] = queue.poll();
44+
}
45+
return newArr;
46+
}
47+
}

0 commit comments

Comments
 (0)