1 개요[ | ]
- Java 힙정렬 구현
- 자바 힙정렬 구현
Java
Copy
public class MyClass {
private static void heapify(int arr[], int length, int i) {
int left = 2*i + 1, right = 2*i + 2;
int temp, largest = i;
if( left<length && arr[left]>arr[largest]) largest = left;
if( right<length && arr[right]>arr[largest]) largest = right;
if( largest != i ) {
temp = arr[i]; arr[i] = arr[largest]; arr[largest] = temp;
heapify(arr, length, largest);
}
}
private static void heapSort(int arr[]) {
int i, temp, length = arr.length;
for(i=length/2-1; i>=0; i--) heapify(arr, length, i);
for(i=length-1; i>=0; i--) {
temp = arr[0]; arr[0] = arr[i]; arr[i] = temp;
heapify(arr, i, 0);
}
}
public static void main(String args[]) {
int arr[] = {9,1,22,4,0,-1,1,22,100,10};
heapSort(arr);
for(int x: arr) System.out.format("%d ",x);
// -1 0 1 1 4 9 10 22 22 100
}
}
2 같이 보기[ | ]
편집자 Jmnote Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.