[DataStructures] 큐(queue) - 우선순위 큐(Priority queue)
Algorithm&DataStructures/Queue 2016. 11. 28. 11:40큐(queue) - 우선순위 큐(Priority queue)
- 큐에 들어있는 값 중 큰 순서대로 밖으로 나온다
1. PriorityQueue.class
1) 초기화
1234567@SuppressWarnings
(
"rawtypes"
)
private
Comparable[] pQueue;
private
int
index =
0
;
public
PriorityQueue(
int
size){
pQueue =
new
Comparable[size];
}
- SuppressWarning 이란 이클립스에게 해당 경고는 무시하라는 표시를 한다
- Comparable 인터페이스형 배열을 만든다
2) insertQueue(Comparable element)
1 2 3 4 5 6 7 8 | public void insertQueue(Comparable element){ if (index == pQueue.length){ System.out.println( "Queue is full" ); return ; } pQueue[index] = element; index++; } |
3) Comparable remove()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public Comparable remove(){ if (index == 0 ){ System.out.println( "Queue is empty" ); return null ; } int maxIndex = 0 ; for ( int i = 1 ; i<index; i++){ if (pQueue[i].compareTo(pQueue[maxIndex]) > 0 ){ maxIndex = i; } } Comparable result = pQueue[maxIndex]; System.out.println( "removing:" +result); index--; pQueue[maxIndex] = pQueue[index]; pQueue[index] = null ; return result; } |
- for문을 이용하여 각각의 요소들을 비교한다
- 가장큰 요소의 인덱스 번호를 max에 저장한 후 그 값을 리턴한다
4) toString(), main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public String toString(){ String str = "[" ; for ( int i= 0 ; i < pQueue.length- 1 ; i++){ str += pQueue[i]+ "," ; } str += pQueue[pQueue.length- 1 ] + "]" ; return str; } public static void main(String[]args){ PriorityQueue pQueue = new PriorityQueue( 5 ); pQueue.insertQueue( 30 ); pQueue.insertQueue( 5 ); pQueue.insertQueue( 10 ); pQueue.insertQueue( 1 ); pQueue.insertQueue( 2 ); System.out.println(pQueue); pQueue.remove(); pQueue.remove(); pQueue.remove(); System.out.println(pQueue); } |
'Algorithm&DataStructures > Queue' 카테고리의 다른 글
[DataStructures] 큐(queue) - 더블링크드리스트를 이용한 데큐(Deque using doubly linked list) (0) | 2016.11.28 |
---|---|
[DataStructures] 큐(Queue) - 데큐 ArrayList(Double-ended queue (Decue using ArrayList)) (0) | 2016.11.22 |
[DataStructures] 큐(Queue) - 동적 큐(DynamicQueue) (0) | 2016.11.22 |
[DataStructures] 큐(Queue) - 간단큐예제(SimpleQueue) (0) | 2016.11.18 |