int main(){ int i, size = 9; int t[] = {63, 73, 25, 19, 44, 2, 59, 38, 10}; printf("Array before creating priority queue:"); for (i = 0; i < size; i++) printf("%d\t",t[i]); build_maxheap(t,size-1); printf("\nNewly built Priority queue : "); for (i = 0; i < size; i++) printf("%d\t",t[i]); i = heap_extract_max(t, size-1); size--; printf("\nExtract maximum:%d\n",i); printf("Priority queue after extract maximum: "); for (i = 0; i < size; i++) printf("%d\t",t[i]); printf("\nEnter a number to be inserted into the priority queue:"); scanf("%d", &i); max_heap_insert(t, i, size-1); size++; printf("Priority queue after insert: "); for (i = 0; i < size; i++) printf("%d\t",t[i]); printf("\n"); return 0; }
void p_queue::heapsort(int array[], int length) { build_maxheap(array, length); for (int i = length - 1; i >= 1; i--) { std::swap(array[0], array[i]); max_heapify(array, --length, 0); } }
p_queue::p_queue(int array[], int length) { for (int i = 0; i < length; i++) { a[i] = array[i]; } heapsize = length; build_maxheap(a, heapsize); }
/* heap sort */ void heapsort( int* a, int n ) { build_maxheap( a, n ); for( int i = n; i >= 2; i-- ) { int buf = a[ i ]; a[ i ] = a[ 1 ]; a[ 1 ] = buf; max_heapify( a, 1, i - 1 ); } }
void hsort(int *A, size_t len) { heap_t *hp; int i; hp = build_maxheap(A, len); for (i = hp->len; i > 1; i--) { swap(hp, 1, i); hp->size--; max_heapify(hp, 1); } free(hp); }
int test_sort_heap() // 堆排序 { // reference: http://proprogramming.org/heap-sort-in-c/ std::vector<int> vec(array_src.begin(), array_src.end()); vec.insert(vec.begin(), -1); build_maxheap(vec, vec.size()-1); heapsort(vec, vec.size()-1); std::vector<int> vecDst(vec.begin() + 1, vec.end()); fprintf(stderr, "heap sort result: \n"); print_result(vecDst); return 0; }
void heapsort(int *const a, const int n) { int *b, heapsize; b = a-1; build_maxheap(b, n); heapsize = n; while (heapsize > 1) { swap(b, 1, heapsize); heapsize -= 1; max_heapify(b, heapsize, 1); } }
int main() { int *arr; int n; scanf("%d",&n); arr = (int*)malloc(sizeof(int)*n); int k; int x; int *temp; int max; int i; for(x=0;x<n;x++) { scanf("%d",&arr[x]); } scanf("%d",&k); temp = (int*)malloc(sizeof(int)*k); for(x=0;x<k;x++) { temp[x] = arr[x]; } build_maxheap(temp,k); max = temp[0]; printf("%d ",max); for(x=k;x<n;x++) { if(arr[x-k] == arr[x]) { printf("%d ",max); } else if(arr[x-k]>arr[x]) { if(arr[x-k]!=max) { printf("%d ",max); } else { for(i=x-k+1;i<=x;i++) { temp[i-x+k-1] = arr[i]; } build_maxheap(temp,k); max = temp[0]; printf("%d ",max); } } else { for(i=x-k+1;i<=x;i++) { temp[i-x+k-1] = arr[i]; } build_maxheap(temp,k); max = temp[0]; printf("%d ",max); } } printf("\n"); return 0; }