堆排序与第K小数最大顶堆

#include <iostream>
#include <cstdio>
using namespace std;

int a[100];

void swap(int &x ,int &y){
    int temp;
    temp = x;
    x = y;
    y = temp;
}

void heap_adjust(int root,int n){//max heap
    int j = root << 1;
    int temp = a[root];
    while(j <= n){
        if( j + 1 <= n && a[j] < a[j+1]) j ++;
        if(a[j] <= temp) break;
        else{
            swap(a[j/2],a[j]);
            //a[j/2] = a[j];
            j <<= 1;
        }
    }
    //a[j/2] = temp;
}

void heap_insert(int num, int k){
    a[k] = num;
    while(k > 1 && a[k] > a[k/2]){//max
        swap(a[k],a[k/2]);
        k >>= 1;
    }
}

void heapsort(int n)
{
	int i,temp;
	for(i=n/2;i>=1;i--)
		heap_adjust(i,n);
	for(i=n-1;i>=1;i--)
	{
		temp=a[i+1];
		a[i+1]=a[1];
		a[1]=temp;
		heap_adjust(1,i);
	}
}

int main()
{
	/*int i,n;
	scanf("%d",&n);
	for(i=1;i<=n;i++)
		scanf("%d",&a[i]);
	heapsort(n);
	for(i=1;i<=n;i++)
		printf("%d ",a[i]);*/
    int i,n=10,m = 4,k = 0,num;
    for(int i = 0 ; i < n ; i ++){
        scanf("%d",&num);
        k ++;
        if(k <= m)
            heap_insert(num,k);
        else{
            if(a[1] > num){
                a[1] = num;
                heap_adjust(1,m);
            }
        }
        printf("a[1] = %d\n",a[1]);
    }
    printf("%d\n",a[1]);
	return 0;
}

你可能感兴趣的:(堆排序)