So, I’ve been struggling for 6 hours to understand this problem by now.
I have this code that searches the minimum value and the maximum value in a list, adding and reducing the range of where will it search for those values, but the list ends up close to be sorted, but they aren’t and I still can’t figure how to fix this.
Basically this is the part where it searches for the minimum and maximum values and their positions.
a = [6, 3, 9, 7, 1, 8, 2, 4, 5]
def minimoMaximo(a):
_min = float('inf')
_max = float('-inf')
pos = 0
posMax = len(a)-1
for i in range(len(a)):
if (a[i] < _min):
_min = a[i]
pos = i
if (a[i] > _max):
_max = a[i]
posMax = i
return pos, posMax
Then it’s supposed to look for the position of the minimum in the list, save its value, delete its current position and insert it to its proper position, then it looks for the position of the maximum and do the same, reducing the range where it searches the minimum and maximum values by every iteration:
medio = ((0 + len(a)-1)//2)
posi = 0
posiMax = 0
posf = len(a)-1
final = len(a)
for i in range (medio):
poseMin = minimoMaximo(a[i:final])
elemMin = a[poseMin[0]+posi]
del a[poseMin[0]+posi]
a.insert(posi, elemMin)
posiMax = posiMax + 1
elemMax = a[poseMin[1]+posiMax]
del a[poseMin[1]+posiMax]
a.insert(posf, elemMax)
posi = posi + 1
posf = posf - 1
final = final - 1
But turns out it doesn’t actually sort the array, I was using pythontutor.com to see where the issue is and it seems like it begins in i = 3 of this line:
for i in range (medio):
It should make elemMax = 7
, but it makes elemMax
to be 4
Visual explanation of Pythontutor.com
It seems to be because posiMax
is 3, so it moves elemMax
one position forward. I tried to add +1 to posiMax
after the whole process, but doing so makes 9 to be in the 3rd position:
Visual explanation of the issue with the 9 value
I’ve tried a lot of things, but I don’t understand how can I make it work, what am I doing wrong??
R_Hydra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.