堆排序

博前感想:

这是我学的一些算法,以及自己思考写的一些代码,但是我的水平实在是有点差,希望大家给我一些建议和意见,这个堆排序是我自己写的,但好像错了,但还是给大家吧。

代码:

#include<iostream>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
#include<set>
#include<time.h>
using namespace std;

int max(int *a, int m, int n)      //要返回下标的形势
{
	int max;
	if (a[m] < a[n])
	{
		max = n;
	}
	else
		max = m;
	return max;
}

void create(int *(&a), int &n)
{
	a = new int[n + 1];
	for (int x = 1; x < n + 1; x++)
	{
		cin >> a[x];
	}
}

void adjust(int *a, int n, int i)        //建大顶堆           //i应该是别的函数调用传进去的参数
{
	//int i=n/2;
	//max(a[2*i],a[2*i+1]);
	int temp;
	if (2 * i + 1 <= n)
	{
		if (a[i] < a[max(a, 2 * i, 2 * i + 1)])
		{
			temp = a[i]; a[i] = a[max(a, 2 * i, 2 * i + 1)]; a[max(a, 2 * i, 2 * i + 1)] = temp;
		}
	}
	else
	{
		if (a[i] < a[2 * i])
		{
			temp = a[i]; a[i] = a[2 * i]; a[2 * i] = temp;
		}
	}

}

void createfirst(int *a, int n)        //初始堆创建正确
{                                       //但是次数好像少了一些,排序没有排完
	int temp;
	for (int j = n; j >= 1; j--)
	{
		for (int i = n / 2/*就是要从这个下标开始*/; i >= 1; i--)
		{
			adjust(a, n, i);
		}
		temp = a[1]; a[1] = a[n]; a[n] = temp;
		//j--;
		n--;
		cout<<a[j]<<" ";              //从后面往前面输出
	}
	cout<<endl;
}

void display(int *a, int n)
{
	for (int i = 1; i < n + 1; i++)
	{
		cout << a[i] << " ";
	}
}

int main()
{
	int *hwq;
	int n;
	clock_t begin,end;double time;
	//int i;
	cin >> n;
	create(hwq, n);
	//adjust(hwq,n,i);
        /*这是我进行测试的时候进行时间的测量
	begin=clock();
	createfirst(hwq, n);
	end=clock();
	time=(double)((double((end)-begin))/CLOCKS_PER_SEC);
	cout<<time<<endl;
        */
	//cout<<t.elapsed()<<endl;
        createfirst(hwq, n);
	display(hwq, n);
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值