1. 程式人生 > >【資料結構】---堆排序

【資料結構】---堆排序

 1、堆排序的基本思想是將一組待排序的數列,排成一個大根堆(小根堆),從而輸出堆頂最大的元素,依次類推,將剩下的元素排成堆,依次輸出最大元素,得到有序序列。

      堆排序的時間複雜度為O(nLog\ n)

2、堆排序演算法實現:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;


typedef struct
{
	int data[100];
	int length;
}SqList;

void Out(SqList *L)
{
	int i;
	for (i = 0; i < L->length; i++)
	{
		printf("%d ", L->data[i]);
	}
}
void Insert(SqList *L, int size)
{
	int i;
	L->length = size;
	printf("輸入%d個元素", size);
	for (i = 0; i < L->length; i++)
	{
		scanf_s("%d", &L->data[i]);
	}
}

void HeapAdjust(SqList *L,int small,int max)
{
	int m, i;
	m = L->data[small];
	for (i = 2 * small + 1; i <= max; i = i * 2 + 1 )
	{
		if (i < max&&L->data[i] < L->data[i + 1])
			i++;
		if (!(m < L->data[i]))
			break;
		L->data[small] = L->data[i];
		small = i;
	}
	L->data[small] = m;
}


void HeapSort(SqList *L)
{
	int i;
	for (i = L->length / 2-1; i >= 0; i--)
	{
		HeapAdjust(L,i,L->length -1 );
	}

	for (i = L->length-1; i > 0; i--)
	{
		swap(L->data[i ], L->data[0]);
		HeapAdjust(L,0,i-1);
	}
	
}
int main()
{
	int size;
	SqList L;
	printf("輸入表的長度:");
	scanf_s("%d", &size);
	Insert(&L, size);
	HeapSort(&L);
	printf("\n堆排序後的元素:");
	Out(&L);
}

3、再走一個java寫的堆排序: 

public static void main(String args[]){
        int n;
        int[] a = {9,4,5,6,2};
        n = a.length-1;
        HeapSort(a,n);
        Out(a);
    }

    public static void Swap(int a[],int i,int j){
        int m;
        m = a[i];
        a[i] = a[j];
        a[j] = m;
    }

    public static void HeapAdjust(int a[], int small, int max) {
        int m,i;
        m = a[small];
        for(i = small*2+1;i<=max;i = i*2+1) {
            if (i < max && a[i + 1] > a[i])
                i++;
            if (!(m < a[i]))
                break;
            a[small] = a[i];
            small = i;
        }
        a[small] = m;
    }

    public static  void HeapSort(int a[],int n){
        int i;
        for(i = n/2-1;i>=0;i--)
            HeapAdjust(a,i,n-1);
        for(i = n;i>0;i--) {
            Swap(a, 0, i);
            HeapAdjust(a, 0, i - 1);
        }
    }
    public static  void Out(int a[]){
        int i;
        for(i  = 0;i<a.length;i++)
            System.out.print(a[i]+" ");
    }