w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Correct algorithm to find the farthest numbers in an array in linear time?

The approach that you have followed in your algorithm has 2*n number of comparisons (n is the total number of numbers in your array) as you are iterating over the array and compare each number with lowest and highest and then updating lowest or highest number accordingly.

You can make this algorithm slightly better by comparing numbers in pair and then compare larger number in pair with highest and smaller number with lowest. So, that for one number pair you end up in doing 3 comparisons. So, total number of comparisons would be 1.5*n.

You can find more details on : FindMinMax





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.