打印

算法疑问

[复制链接]
869|1
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
gxgclg|  楼主 | 2012-3-18 10:02 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
如下一段代码对一个数组做原地桶排序,请大家帮忙分析下其算法复杂度是O(N)还是O(N2)?内层while循环的算法复杂度如何分析?
#include <iostream>
using namespace std;
int main(){
    int a[10] = {3,2,4,9,6,1,0,8,7,-1};
    int temp;
    int temp_val;
    for(int i = 0; i < 10; i++){
        if(a[i] != i){
            temp_val = temp = a[a[i]];//临时变量先存储需要更换的值
            a[a[i]] = a[i];
            a[i] = temp;
            }
        while(a[temp_val] != temp_val){
            temp = a[temp_val];
            a[temp_val] = temp_val;
            temp_val = temp;
            if(temp_val == -1) break;
        }
    }
    for(int j = 0; j < 10; j++){
        cout<<a[j]<<endl;
        if(a[j] != j) cout<<"the miss number is"<<j<<endl;
    }
    return 0;
}

相关帖子

沙发
无冕之王| | 2012-3-18 10:30 | 只看该作者
内层while(貌似其实完全把if和while合并)每执行一次保证能把一个数据挪到正确的位置,所以这个肯定是O(N)。另一个角度说这个执行次数必然小于10次if加10次while。没太仔细看,不过这个程序感觉对-1的判断有点问题

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

177

主题

1653

帖子

1

粉丝