C언어 힙정렬 구현

1 개요[ | ]

C언어 힙정렬 구현
#include<stdio.h>
void heap_heapify(int a[], int size, int i) {
	int temp, left=2*i+1, right=2*i+2, largest=i;
	if( left<size && a[left]>a[largest] ) largest=left;
	if( right<size && a[right]>a[largest] ) largest=right;
	if( largest == i ) return;
	temp=a[i]; a[i]=a[largest]; a[largest]=temp;
	heap_heapify(a, size, largest);
}
void heap_sort(int a[], int size) {
	for(int i=size/2-1; i>=0; i--) heap_heapify(a, size, i);
	int temp;
	for(int i=size-1; i>=0; i--) {
		temp=a[0]; a[0]=a[i]; a[i]=temp;
		heap_heapify(a, i, 0);
	}
}
int main() {
	int arr[] = {9,1,22,4,0,-1,1,22,100,10};
	int size = sizeof(arr)/sizeof(int);
	heap_sort(arr, size);
	for(int i=0; i<size; i++) printf("%d ", arr[i]);
	// -1 0 1 1 4 9 10 22 22 100 
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}