0

The following code is where I face errors:

array = [16,1,2,3,4,5] n = len(array) swapped = True while swapped == True: swapped = False for inner_index in range(1,n): first_number = array[inner_index - 1] second_number = array[inner_index] if first_number > second_number: first_number, second_number = second_number, first_number swapped = True print(array) 

This above code results in an infinite loop. Checking with python tutor, I noticed that it swaps the element but doesn't really "update" it in my array.

However, when I do the following, my code seems to be running:

Optimized Bubble sort algorithm code

array = [16,1,2,3,4,5] n = len(array) swapped = True #Dont forget boolean values start with a capital letter while swapped == True: swapped = False for inner_index in range(1,n): if array[inner_index - 1] > array[inner_index]: array[inner_index - 1], array[inner_index] = array[inner_index], array[inner_index-1] swapped = True print(array) 

What's the difference between the two?

1
  • you're not reassigning your variables into the array... Commented Sep 13, 2022 at 19:34

2 Answers 2

0
first_number = array[inner_index - 1] 

Here, first_number is just referencing the value from the array. If you reassign first_number, it's value won't automatically update in the array (since it's not a pointer to the specific memory location).

In the second approach, the values are updated directly into the array, so it reflects the correct result.

Sign up to request clarification or add additional context in comments.

Comments

0

In the first code, you are updating the value of a variable, and then not assigning it back to the list. In the second example, you are directly assigning an element in the list to the value you want.

Change this line (in the first code):

first_number, second_number = second_number, first_number 

To:

array[inner_index - 1], array[inner_index] = second_number, first_number 

2 Comments

Gotcha thanks! How could I modify the first code then to reassign variables back into the list?
@YashMehta That's exactly how you would do it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.