0

I'm supposed to do it with a for cycle. Maybe it's too late but I just can quite start it. I'm supposed to rearrange it if an item is greater than the one next to it, they should change space.

l = [ 12, 51, 10, 46, 8, 17, 39 ]
for i in range(len(l)):
  if i > i + 1: 

this is as far as I've gotten.

shadowtalker
  • 12,529
  • 3
  • 53
  • 96
  • 3
    Try taking a look at some [sorting algorithms](https://en.wikipedia.org/wiki/Sorting_algorithm) and how to implement one of the simplest sorting algorithms, [bubble sort](http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html), in Python – sleighty Mar 28 '19 at 21:03

1 Answers1

0

What you are doing is called a Bubble Sort.

Try this:

for _ in l: 
  for i in range(len(l)):
    if i<len(l)-1 and l[i] > l[i+1]:
      l[i], l[i+1] = l[i+1], l[i]

You have to iterate over every item in the list once, and swap it with its neighbor. Doing this once however will only partially sort the list. You have to do this the same number of times as elements in the list to guarantee your list will be fully sorted (That is why there is the extra for loop with the _).

Salvatore
  • 10,815
  • 4
  • 31
  • 69