【数据结构】---堆排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40567229/article/details/81159903

 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]+" ");
    }

猜你喜欢

转载自blog.csdn.net/weixin_40567229/article/details/81159903