算法导论读后感-之同时查找最大数与最小数

来源:互联网 发布:西蒙网络面板接线图 编辑:程序博客网 时间:2024/05/22 01:40

在数组中查询最大数与最小数,通常的做法需要遍历两次数组,进行2n次比较。但在算法导论中,介绍了一个更为高效的算法,只需要比较3*n/2次。虽然两种算法均为线性复杂度,但效率仍然可提高25%。
其思想为将数组中的元素成对处理,每次处理两个元素,进行1次比较,将大的数和最大值比较,将小的数和最小值比较,因此,处理两个元素,进行了3次比较。比原来每个数要比较1次最大值1次最小值就有提升。具体算法代码如下:

void RandomSelect::selectMaxAndMin(int *a, int length, int &maxIndex, int &minIndex){    maxIndex = 0;    minIndex = 0;    int maxValue = a[0];    int minValue = a[0];    for (int i = 0; i < length/2; i++)    {        if (a[2*i] < a[2*i + 1])        {            if (a[2*i] < minValue)            {                minValue = a[2*i];                minIndex = 2 * i;            }            if (a[2*i + 1] > maxValue)            {                maxValue = a[2*i + 1];                maxIndex = 2 * i + 1;            }        }        else        {            if (a[2*i] > maxValue)            {                maxValue = a[2*i];                maxIndex = 2 * i;            }            if (a[2*i + 1] < minValue)            {                minValue = a[2*i + 1];                maxIndex = 2 * i + 1;            }        }    }    if (length % 2 == 1)    {        if (a[length - 1] > maxValue)        {            maxValue = a[length-1];            maxIndex = length - 1;        }        if (a[length - 1] < minValue)        {            minValue = a[length-1];            minIndex = length - 1;        }    }}
阅读全文
0 0