【C++】希尔排序、快速排序、堆排序的每步排序

#include
using namespace std;

#define MAXSIZE 20
typedef int KeyType;
typedef struct {
	KeyType key;
}RedType;

typedef struct {
	RedType r[MAXSIZE+1];
	int length;
}SqList;

//希尔排序
int ShellInsert(SqList &L, int dk)
{
	int i, j;
	for(i=dk+1;i<=L.length;++i)
		if (L.r[i].key < L.r[i - dk].key) {
			L.r[0] = L.r[i];
			for (j = i - dk; j > 0 && (L.r[0].key < L.r[j].key); j = j - dk)
				L.r[j + dk] = L.r[j];
			L.r[j + dk] = L.r[0];
		}
	return 1;
}

int Shellsort(SqList& L, int dlta[], int t)
{
	int k;
	for (k = 0; k < t; ++k)
	{
		ShellInsert(L, dlta[k]);
		for (int i = 1; i <= L.length; i++)///
			cout << L.r[i].key << ' ';
		cout << endl;
	}
	return 1;
}

//快速排序
int Partition(SqList& L, int low, int high)
{
	int pivotkey;
	L.r[0] = L.r[low];
	pivotkey = L.r[low].key;
	while (low = pivotkey)--high;
		L.r[low] = L.r[high];
		while (low < high && L.r[low].key <= pivotkey)++low;
		L.r[high] = L.r[low];
	}
	L.r[low] = L.r[0];
	return low;
}

void QSort(SqList& L, int low, int high)
{
	int pivotloc;
	if (low < high) {
		pivotloc = Partition(L, low, high);
		for (int i = 1; i <= L.length; i++)
			cout << L.r[i].key << ' ';
		cout << endl;
		QSort(L, low, pivotloc - 1);
		QSort(L, pivotloc + 1, high);
	}
}

void Quicksort(SqList& L)
{
	QSort(L, 1, L.length);
}

//堆排序
void HeapAdjust(SqList& L, int s, int m)
{
	RedType rc = L.r[s];
	int j;
	for (j = 2 * s; j <= m; j *= 2)
	{
		if (j < m && L.r[j].key < L.r[j + 1].key)++j;
		if (rc.key >= L.r[j].key)break;
		L.r[s] = L.r[j]; s = j;
	}
	L.r[s] = rc;
}

void CreaHeap(SqList& L)
{
	int n = L.length;
	for (int i = n / 2; i > 0; --i)
	{
		HeapAdjust(L, i, n);
	}
}

void HeapSort(SqList& L)
{
	CreaHeap(L);
	RedType x;
	for (int i = L.length; i > 1; --i)
	{
		x = L.r[1];
		L.r[1] = L.r[i];
		L.r[i] = x;
		HeapAdjust(L, 1, i - 1);
		for (int j = 1; j <= L.length; j++)
			cout << L.r[j].key << ' ';
		cout << endl;
	}
}

int main()
{
	SqList L,M,N;
	//希尔排序输出
	int dlta[10];//用于存放增量的取值
	int t;//增量取值的个数
	int i;
	cout << "希尔排序进行中...请输入待排序列长度和输入数据:";
	cin >> L.length;
	for (i = 1; i <= L.length; i++)
		cin >> L.r[i].key;
	cout << "输入增量的个数:";
	cin >> t;
	cout << "输入增量d的t个取值:";
	for (i = 0; i < t; i++)
		cin >> dlta[i];
	cout << "每次排序的结果为:" << endl;
	Shellsort(L, dlta, t);

	//快速排序输出
	int j;
	cout << "快速排序进行中...请输入待排序列长度和输入数据:";
	cin >> M.length;
	for (j = 1; j <= M.length; j++)
		cin >> M.r[j].key;
	int low = 1;
	int high = M.length; 
	cout << "每次排序的结果为:" << endl;
	Quicksort(M);

	//堆排序输出
	int k;
	cout << "堆排序进行中...请输入待排序列长度和输入数据:";
	cin >> N.length;
	for (k = 1; k <= N.length; k++)
		cin >> N.r[k].key;
	cout << "每次排序的结果为:" << endl;
	HeapSort(N);
	return 1;
}

你可能感兴趣的:(c++,算法,排序算法)