May-08-2017, 08:59 PM
(May-08-2017, 02:20 AM)jhall710 Wrote: I keep getting the same output [4, 5, 2, 6, 8] instead of [2, 4, 5, 6, 8]
here's my code
list_ = [6,8,4,5,2] I = 0 J = 999 while I < 5: J = 0 while J < 4: list_[J], list_[J + 1] = list_[J + 1], list_[J] # This if statement will check values in list and then... J += 1 I += 1 print(list_)
I get the output desired output keeping the IF statement....which I see you removed. The purpose of the If statement is to check the values. Your code does no checking of the values, its just random swapping, which is why you don't get the desired result. Below I have attached an example
list_ = [6,8,4,5,2] I = 0 J = 999 while I < 5: J = 0 while J < 4: if list_[J]> list_[J+1]: # This if statement will check values in list and then... list_[J],list_[J+1] = list_[J+1],list_[J]# swap the values if the item after it has a lesser value J += 2 # it should skip over the swap it just made. else: J += 1 # keep moving forward 1 I += 1 # so the loop doesn't continue forever print(list_)