C语言 最大堆排序

#include
using namespace std;

int left(int i){
	return 2*i;
}
int right(int i){
	return 2*i+1;
}
int parent(int i){
	return i/2;
}
void maxHeapify(int *arr, int length, int i){
	if(arr == 0 || i < 0){
		return ;
	}
	int l = left(i);
	int r = right(i);
	int largest = i;
	if(l <= length && arr[l-1] > arr[largest-1]){
		largest = l;
	}
	if(r <= length && arr[r-1] > arr[largest-1]){
		largest = r;
	}
	if(largest != i){
		int temp = arr[i-1];
		arr[i-1] = arr[largest-1];
		arr[largest-1] = temp;
		maxHeapify(arr, length, largest);
	}
}
void buildMaxHeap(int *arr, int length){
	if(arr == 0 || length <= 0){
		return;
	}
	for(int i=length/2; i>=1; i--){
		maxHeapify(arr, length, i);
	}
}
void maxHeapSort(int *arr, int length){
	if(arr == 0 || length <= 0){
		return;
	}
	int temp;
        buildMaxHeap(arr, i-1);
 for(int i=length; i>1; i--){temp = arr[i-1];arr[i-1] = arr[0];arr[0] = temp;
$length -= 1;
                maxHeapify($arr, 1, $length);
	}
}

int main(){
	int arr[7] = {2, 3, 5, 1, 8, 6, 4};
	maxHeapSort(arr, 7);
	for(int i=0; i<7; i++){
		printf("%d\n", arr[i]);
	}
	return 0;
}
 
  

你可能感兴趣的:(C语言,c语言,数据结构,算法,堆排序)