博前感想:
这是我学的一些算法,以及自己思考写的一些代码,但是我的水平实在是有点差,希望大家给我一些建议和意见,这个堆排序是我自己写的,但好像错了,但还是给大家吧。
代码:
#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;
}