Harrison Croaker Harrison Croaker - 1 year ago 55
Python Question

How do I find the highest value and swap it with the end value in an array?

This is my python code so far and the result I'm getting at the end is [5, 2, 3, 12, 1, 12].

array = [5,2,3,12,1,6]
temp = ''
lastvalue = 5
highestvalue = array[0]


while i<5:

if array[i]>highestvalue:
highestvalue = array[i]


temp = array[5]
array[5] = highestvalue
highestvalue = temp


I'm looking for the result [5,2,3,6,1,12]

Answer Source

temp is a separate variable, not an array element. Instead, identify the position needed, and swap with that. I assume that you're doing it "the hard way" (without min and max methods) for homework?

array = [5,2,3,12,1,6]
highest_pos = 0

for i in range(len(array)):
    if array[i] > array[highest_pos]:
        highest_pos = i

temp = array[-1]
array[-1] = array[highest_pos]
array[highest_pos] = temp


Note also that I've changed your 5 references to use either the list length or the final element, -1. Negative numbers index a list from the opposite (right) end.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download