順序表的堆排序

xiaoxiangMilisa發表於2020-12-16
#include<iostream>
using namespace std;

const int MaxSize = 20;

typedef int KeyType;
typedef struct {//線性表的結構
	KeyType key;
	int data;
}RecType;

typedef struct {//線性表
	RecType data[MaxSize];
	int length;
}Sqlist;

void CreateList(Sqlist*& L, int a[], int n) {//建立順序表
	int i = 0, k = 0;
	L = (Sqlist*)malloc(sizeof(Sqlist));
	while (i < n)
	{
		L->data[k].key = a[i];
		k++, i++;
	}
	L->length = k;
}

void sift(RecType R[], int low, int high)
{
	int i = low, j = 2 * i;
	RecType tmp = R[i];
	while (j <= high)
	{
		if (j < high && R[j].key < R[j + 1].key)
			j++;
		if (tmp.key < R[j].key)
		{
			R[i] = R[j];
			i = j;
			j = 2 * i;
		}
		else break;
	}
	R[i] = tmp;
}

void HeapSort(RecType R[], int n)
{
	int i;
	for (i = n / 2; i >= 1; i--)
		sift(R, i, n);
	for (i = n; i >= 2; i--)
	{
		swap(R[1], R[i]);
		sift(R, 1, i - 1);
	}
}

void DestroyList(Sqlist*& L) {//銷燬順序表
	free(L);
}

int main()
{
	int a[] = { NULL,6,8,7,9,0,1,3,2,4,5 };
	int n = 11;
	Sqlist* b;
	CreateList(b, a, n);
	HeapSort(b->data, n-1);
	for (int i = 1; i < n; i++) {
		cout << b->data[i].key;
		cout << " ";
	}
	DestroyList(b);
	return 0;
}

相關文章