Friday, March 21, 2014

Heap sort

#ifndef _HEAP_SORT_H
#define _HEAP_SORT_H

#define _BOTTOM_TOP

#define LEFT(i) (((i)<<1)+1)
#define RIGHT(i) (((i)<<1)+2)
#define PARENT(i) (((i+1)>>1)-1)

void reheap_down(int * arr, int start, int end) {
    if(start >= end) return;
    int root=start;
    while(LEFT(root)<=end) {
int to_swap = LEFT(root);
if(RIGHT(root)<=end &&
arr[LEFT(root)] < arr[RIGHT(root)]) {
   to_swap = RIGHT(root);
}

if(arr[root] < arr[to_swap]) {
   swap(arr+root, arr+to_swap);
   root = to_swap;
} else {
   break;
}

    }
}

void reheap_up(int * arr, int start, int end) {
    if(start >= end) return;
    int child = end;
    int par = PARENT(child);
    while(par > -1) {
if(arr[par] < arr[child]) {
   swap(arr+par, arr+child);
   child = par;
   par = PARENT(child);
} else {
   break;
}
    }
}

void make_heap(int * arr, int size) {
#ifdef BOTTOM_UP
    int root = PARENT(size-1);
    while(root>-1) {
reheap_down(arr, root, size-1);
root--;
    }
#else
    int end = 0;
    while(end<size) {
reheap_up(arr, 0, end);
end++;
    }
#endif
}

void sort(int * arr, int size) {

    make_heap(arr, size);

    int i = size-1;
    for(i = size - 1; i>=0; i--) {
swap(arr, arr+i);
reheap_down(arr, 0, i-1);
//print_arr(arr, size);
    }
}

#endif

No comments:

Post a Comment