-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.java
More file actions
102 lines (78 loc) · 2.86 KB
/
Program.java
File metadata and controls
102 lines (78 loc) · 2.86 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package practice.heap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Program {
private static class PriorityQueue<T extends Comparable<T>> {
private List<T> memory = new ArrayList<>();
public PriorityQueue() { memory.add(null); }
public void push(T item) {
memory.add(item);
int index = memory.size() - 1;
int parentIndex = index / 2;
while (parentIndex >= 1 && compareIndex(parentIndex, item)) {
Collections.swap(memory, parentIndex, index);
index = parentIndex;
parentIndex /= 2;
}
}
public T pop() {
final T item = memory.get(1);
int last = memory.size() - 1;
memory.set(1, memory.get(last));
memory.remove(last--);
int index = 1;
int childIndex = getChildIndex(index * 2);
while (childIndex <= last && compareIndex(index, childIndex)) {
Collections.swap(memory, index, childIndex);
index = childIndex;
childIndex = getChildIndex(index * 2);
}
return item;
}
private boolean compareIndex(int indexA, int indexB) {
return memory.get(indexA).compareTo(memory.get(indexB)) > 0;
}
private boolean compareIndex(int indexA, T value) {
return memory.get(indexA).compareTo(value) > 0;
}
private int getChildIndex(int index) {
final int size = memory.size();
if (index >= size) return size;
if (index == size - 1) return index;
if (compareIndex(index, index + 1)) index++;
return index;
}
public boolean isEmpty() { return memory.size() < 2; }
@Override public String toString() { return "PriorityQueue " + memory; }
}
private static <T extends Comparable<T>> Object[] heapSort(T[] arr) {
// 입력된 데이터를 모두 최소 힙에 입력한다
PriorityQueue<T> priorityQueue = new PriorityQueue<>();
for (T item : arr) priorityQueue.push(item);
System.out.println(priorityQueue);
// 최소 힙에 있는 데이터를 모두 pop 하여 정렬한다
List<T> result = new ArrayList<>();
while (!priorityQueue.isEmpty()) {
result.add(priorityQueue.pop());
System.out.println(priorityQueue);
}
// 결과 반환
return result.toArray();
}
public static void main(String[] args) {
// 정렬할 배열 준비
Integer[] arr = {4, 3, 5, 6, 3, 6, 899, 32, 54, 6, 7};
// 최소 힙 정렬
Object[] sortedArr = heapSort(arr);
System.out.println();
// 정렬 결과를 정수 배열로 변환하여 출력
Integer[] sortedIntArr = Arrays.copyOf(sortedArr, arr.length, Integer[].class);
System.out.println("heap sort: " + Arrays.toString(sortedIntArr));
// 결과 비교
Arrays.sort(arr);
System.out.println("sort : " + Arrays.toString(arr));
System.out.println("compare : " + Arrays.equals(arr, sortedIntArr));
}
}