首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

排序次数解决方法

2012-03-31 
排序次数插入 和归并 排序 对数组3, 1,4,1,5,9,6,5进行从小到大排序 需要多少次比较答案是 12,14不明白[解

排序次数
插入 和 归并 排序 对数组
3, 1,4,1,5,9,6,5
进行从小到大排序 需要多少次比较

答案是 12,14
不明白

[解决办法]
当然了。你记得算法就会画。这种题不就是变相地考你会不会写这个排序算法吗。
其实你可以写一个trace程序,跟踪比较次数,每调用一次<号,统计数+1。

C/C++ code
#include<iostream>class SortTracer{    double value;    int generation;    static long n_created;    static long n_destroyed;    static long n_assigned;    static long n_compared;    static long n_max_live;    static void update_max_live(){        if(n_created-n_destroyed>n_max_live){            n_max_live=n_created-n_destroyed;        }    }public:    static long creations(){        return n_created;    }    static long destructions(){        return n_destroyed;    }    static long assignments(){        return n_assigned;    }    static long comparions(){        return n_compared;    }    static long max_live(){        return n_max_live;    }public:    SortTracer(double k):value(k){        generation=1;        ++n_created;        update_max_live();    }    SortTracer(SortTracer& b):value(b.value),generation(b.generation+1){        ++n_created;        update_max_live();    }    ~SortTracer(){        ++n_destroyed;        update_max_live();    }    SortTracer& operator=(SortTracer& b){        ++n_assigned;        value=b.value;        return *this;    }    friend bool operator<(SortTracer& a,SortTracer& b){        n_compared++;        return a.value<b.value;    }    friend bool operator==(SortTracer& a,SortTracer& b){        n_compared++;        return a.value==b.value;    }    friend bool operator>(SortTracer& a,SortTracer& b){        n_compared++;        return a.value>b.value;    }    friend bool operator<=(SortTracer& a,SortTracer& b){        n_compared++;        return a.value<=b.value;    }    friend bool operator>=(SortTracer& a,SortTracer& b){        n_compared++;        return a.value>=b.value;    }    double val(){        return value;    }};long SortTracer::n_created=0;long SortTracer::n_destroyed=0;long SortTracer::n_max_live=0;long SortTracer::n_assigned=0;long SortTracer::n_compared=0; 

热点排行