Home > Mobile >  Other way to get the 1st and 2nd to the highest and to the lowest but not using array sorting
Other way to get the 1st and 2nd to the highest and to the lowest but not using array sorting

Time:10-24

User must input 10 integers and I need to get the first and second to the highest & first and second to the lowest number between those 10 integers entered. I had in mind to sort and then print but I need to use something that is not array sorting.

Thanks in advance.

CodePudding user response:

Try this

largest = second = -999;
 
    for i in range(0, 10):
        largest = max(largest, arr[i]);
 
    for i in range(0, 10):
        if (arr[i] != largest):
            second = max(second, arr[i]);
 
    if (second == -999):
        print("There is no second "  
              "largest element");
    else:
        print("The second largest "  
              "element is \n", second);

CodePudding user response:

You can achieve this in simple way like below slightly borrowing idea of Kadane's Algorithm:

Idea here is first set min1, min2, max1, max2, and then iterating the list keep update those 4 values.

data = [6, 10, 1, 7, 8, 2, 3, 4, 5, 9]

max1 = min(data[0], data[1])
max2 = max(data[0], data[1])
min1 = min(data[0], data[1])
min2 = max(data[0], data[1])

for i in range(2, len(data)):
    if data[i] > max2:
        max1 = max2
        max2 = data[i]
    if data[i] > max1:
        max1 = data[i]

    if data[i] < min1:
        min2 = min1
        min1 = data[i]
    if min1 < data[i] < min2:
        min2 = data[i]


print(max1, max2) // prints 9, 10
print(min1, min2) // prints 1, 2
  • Related