+ 1
If someone can explain me better this code below
X = [2, 1, 21, 13, 233, 144, 0, 3, 8, 5, 89, 34, 1, 55] for i in range(len(X)): for j in range(i+1 , len(X)): if X[i] >= X[j] : X[i],X[j] = X[j], X[i] print(X) This code sort the list with for loop but I don t understand why I need to add +1 to i , and this line of code : X[i],X[j] = X[j], X[i] if I understood right is swiping values.
6 Respuestas
+ 3
+1 is there to not compare element at index i with itself
+ 3
Andrei Macovei ,
here are 2 links to short tutorials from the community section:
https://www.sololearn.com/learn/649/?ref=app
https://www.sololearn.com/learn/701/?ref=app
+ 2
Your guess with swapping values is right.
+ 2
j = i+1 is next index to i
Each value at index i is compared with next proceeding elements in the list.
(Because Previous elements (0 to i) are already been searched, so skip.) Yes swaps.
+ 2
Thank you guys
+ 2
For each index i of list X we check if element at i is greater than any element to the right. If it is we swap them.