关于算法的时间问题

engineersun 2015-11-19 03:12:25
写了一个堆排序,提交的时候总是说运行时间过长,不通过。
然后找了一个通过的代码,感觉自己的代码和这个代码的区别就是一个是循环,一个是递归调用。
我觉得用循环代替递归调用应该是能节省时间的呀,为什么我的代码会不如这段递归调用 的代码呢?
我的代码的时间主要耗在了哪里了呢?
自己在swap函数中加了计数,感觉一样的数组,自己的代码swap次数更少,为什么会运行时间反而长呢?

随帖附上代码:
//1、我自己写的堆排序的代码
#include <iostream>
using namespace std;


class HeapSort {
public:
//int count = 0;
void swap(int &x,int &y) {
if(x==y)return;
int t = x;
x = y;
y = t;
//count++;
}
void heapjust(int *A,int n,int index) {
int lchild = index * 2 + 1;
int rchild = lchild + 1;
while (rchild < n) {
if(A[index] >= A[lchild] && A[index] >= A[rchild]) return;
if (A[lchild] > A[rchild]) {
swap(A[index],A[lchild]);index = lchild;
}
else if (A[lchild] < A[rchild]) {
swap(A[index],A[rchild]);
index = rchild;
}
lchild = index * 2 + 1;
rchild = lchild + 1;

}

if (lchild < n && A[lchild] > A[index])
swap(A[index],A[lchild]);
return ;
}


int* heapSort(int* A, int n) {
if(n < 2) return A;
for (int i= n/2 - 1;i > 0; i--) {
heapjust(A,n,i);
}


while (n > 0) {
swap(A[n - 1],A[0]);
n--;
heapjust(A,n,0);

}
//cout<<"count="<<count<<endl;
return A;// write code here
}
};
int main() {
int a[] = {3,2,5,1,4};
HeapSort h;
h.heapSort(a,5);
for (int i = 0; i < 5; i++) {
cout<<a[i]<<endl;
}
// your code goes here
return 0;
}


//--------------------------------------------------------------
//2、通过的代码
#include <iostream>
using namespace std;


class HeapSort {
public:
//int count = 0;

int* heapSort(int* A, int n) {
// write code here
if(n<2)return A;
for(int i = n/2-1;i>=0;--i)
{
heapfy(A,i,n);
}
for(int i = n-1;i>=1;--i)
{
swap(A[0],A[i]);
heapfy(A,0,i);

}
//cout<<"count="<<count<<endl;
return A;
}
void swap(int &x,int &y)
{
if(x==y)return;
int t = x;
x = y;
y = t;
//count++;
}
void heapfy(int* A, int index, int size)
{
int left = 2*index+1;
int right = left+1;
int largest = index;
if(left<size && A[left]>A[index]){largest = left;}
if(right<size && A[largest]<A[right]){largest = right;}
if(largest != index)
{
swap(A[index],A[largest]);
heapfy(A,largest,size);
}
}
};
int main() {
int a[] = {3,2,5,1,4};
HeapSort h;
h.heapSort(a,5);
for (int i = 0; i < 5; i++) {
cout<<a[i]<<endl;
}
// your code goes here
return 0;
}
...全文
69 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2015-11-20
  • 打赏
  • 举报
回复
无profiler不要谈效率!!尤其在这个云计算、虚拟机、模拟器、CUDA、多核 、多级cache、指令流水线、多种存储介质、……满天飞的时代!
707wk 2015-11-19
  • 打赏
  • 举报
回复
你从哪看出循环比递归快的→_→

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧