Generate an optimized Python program that sorts a list of integers using bubble sort.…
- User
Generate an optimized Python program that sorts a list of integers using bubble sort. [3, 5, 1, 4, 7]
Assistant
Problem: Generate an optimized Python program that sorts a list of integers using bubble sort. [3, 5, 1, 4, 7]
Let me implement this solution.
code# Last i elements are already in place for j in range(0, n - i - 1): # Traverse the array from 0 to n-i-1 # Swap if the element found is greater than the next element if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] swapped = True # If no two elements were swapped by inner loop, then break if not swapped: break return arrInput list
data = [3, 5, 1, 4, 7]
Sort the list
sorted_data = optimized_bubble_sort(data)
Print the result
print(sorted_data)
Output:
code[1, 3, 4, 5, 7]