堆排序(C语言)

#include
#include
#define LEFT(i)  (i * 2) 
#define RIGHT(i) (i * 2 + 1) 
#define cmp >       //大于号构建大顶堆,小于号构建小顶堆
#define ELE_NUM 500 
#define RANGE   1000 
void down_update(int* data, int i, int n) {
	while (LEFT(i) <= n) {
		int ind = i;
		if (data[LEFT(i)] cmp data[ind]) ind = LEFT(i);
		if (RIGHT(i) <= n && data[RIGHT(i)] cmp data[ind]) ind = RIGHT(i);
		if (ind == i) break;
		int tem = data[i];
		data[i] = data[ind];
		data[ind] = tem;
		i = ind;
	}
	return;
}

//堆排序
void heap_sort(int* ar, int n) {
	int* data = ar - 1;

	//要用堆排序,先建堆,采取线性建堆法
	for (int i = n / 2; i >= 1; i--) {
		down_update(data, i, n);
	}

	//堆建好后,依次弹出堆顶元素
	for (int i = n; i >= 2; i--) {
		int tem = data[1];
		data[1] = data[i];
		data[i] = tem;
		down_update(data, 1, i - 1);
	}
	return;
}

int main() {
	srand(time(0));
	int ysy[ELE_NUM] = { 0 };
	for (int i = 0; i < ELE_NUM; i++) {
		ysy[i] = rand() % RANGE;
	}
	heap_sort(ysy, ELE_NUM);
	for (int i = 0; i < ELE_NUM; i++) {
		if (i != 0 & i % 20 == 0) printf("\n");
		printf("%d ", ysy[i]);
	}
	return 0;
}

你可能感兴趣的:(排序,算法)