0
I need help!!!!!
Hi, guys! I need your help. I study python very short time and I need to do my homework, but I don’t understand. Can u help? 1)How do I change these algorithms so that the array elements are sorted in descending order? The alogorhythms are similar to the one I wrote below 2) Konstantin suggested using such a nested loop to sort the array. How exactly will the elements be sorted? Will the serving be done correctly? for i in range(N-1): for j in range(N-1): if A[j] < A[j+1]: A[j], A[j+1] = A[j+1], A[j] It is python.
3 Respostas
+ 2
This is a pretty simple sort called bubble sort, if you don't quite understand it, watch this 1 min animation to get the idea of how it works:
https://www.youtube.com/watch?v=nmhjrI-aW5o
The algorithm you wrote actually sorts the array in descending order (you can replace "<" with ">" in line 3 to make it sort the other way), also to optimize it you can change the line 2 to this:
for j in range(N-1-i):
+ 2
Simply test it, you will see what it does:
A=[1, 4, 5, 3, 7, 3]
N = len(A)
for i in range(N-1):
for j in range(N-1):
if A[j] < A[j+1]:
A[j], A[j+1] = A[j+1], A[j]
print (A)
+ 1
You are my hero, dude. Thank you so much from Russia ❤️❤️