寻找第二大数字阵列最多n +log₂(N)

编程入门 行业动态 更新时间:2024-10-07 15:28:47
本文介绍了寻找第二大数字阵列最多n +log₂(N)-2比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

正在给定为输入的n不同数字,其中n是2的幂给出一个算法标识阵列中的第二大数量的未分类的数组,以及使用最多n +log₂(正) - 2比较。

解决方案
  • 开始,在奇数和偶数位置比较n个元素数组的元素,并确定每对的最大元素。此步骤需要n / 2比较。现在你只拿到N ​​/ 2个元素。继续两两比较,以获得N / 4,N / 8,...元素。停车时,最大的元素被发现。此步骤需要总数为n / 2 + N / 4 + N / 8 + ... + 1 = n-1个比较。
  • 在previous一步,最大的元素立即与log₂(n)的其他元素进行比较。您可以确定最大的这些元素的log₂(N)-1的比较。这将是在阵列中第二大数目。
  • 例如:8个数字阵列[10,9,5,4,11,100,120,110]

    1的水平比较:10.9] - > 10 [5,4] - > 5,[11100] - > 100, [120,110] - > 120

    2的水平比较:[10.5] - > 10 [100,120] - > 120

    3级比较: [10120] - > 120

    最大是120.有人立刻相比:10(3级),100(2级),110(1级)

    步骤2应该找的10,100最大的,和110这是110。这是第二大因素。

    You are given as input an unsorted array of n distinct numbers, where n is a power of 2. Give an algorithm that identifies the second-largest number in the array, and that uses at most n+log₂(n)−2 comparisons.

    解决方案

  • Start with comparing elements of the n element array in odd and even positions and determining largest element of each pair. This step requires n/2 comparisons. Now you've got only n/2 elements. Continue pairwise comparisons to get n/4, n/8, ... elements. Stop when the largest element is found. This step requires a total of n/2 + n/4 + n/8 + ... + 1 = n-1 comparisons.
  • During previous step, the largest element was immediately compared with log₂(n) other elements. You can determine the largest of these elements in log₂(n)-1 comparisons. That would be the second-largest number in the array.
  • Example: array of 8 numbers [10,9,5,4,11,100,120,110].

    Comparisons on level 1: [10,9] ->10 [5,4]-> 5, [11,100]->100 , [120,110]-->120.

    Comparisons on level 2: [10,5] ->10 [100,120]->120.

    Comparisons on level 3: [10,120]->120.

    Maximum is 120. It was immediately compared with: 10 (on level 3), 100 (on level 2), 110 (on level 1).

    Step 2 should find the maximum of 10, 100, and 110. Which is 110. That's the second largest element.

    更多推荐

    寻找第二大数字阵列最多n +log₂(N)

    本文发布于:2023-11-30 15:19:56,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1650486.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:最多   阵列   第二大   数字   log

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!