Find the 2nd largest element in an array with minimum number of comparisons

后端 未结 24 1348
清酒与你
清酒与你 2020-11-28 01:03

For an array of size N, what is the number of comparisons required?

24条回答
  •  甜味超标
    2020-11-28 01:10

    Use Bubble sort or Selection sort algorithm which sorts the array in descending order. Don't sort the array completely. Just two passes. First pass gives the largest element and second pass will give you the second largest element.

    No. of comparisons for first pass: n-1

    No. of comparisons for first pass: n-2

    Total no. of comparison for finding second largest: 2n-3

    May be you can generalize this algorithm. If you need the 3rd largest then you make 3 passes.

    By above strategy you don't need any temporary variables as Bubble sort and Selection sort are in place sorting algorithms.

提交回复
热议问题