Bubble Sort Algorithm in Python: Code and Explanation
Here's a sample implementation of bubble sort in Python:
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# 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]
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print('Sorted array is:')
for i in range(len(arr)):
print('%d' %arr[i])
This implementation takes an array 'arr' as input, and uses a nested loop to compare adjacent elements and swap them if they are in the wrong order. The outer loop runs 'n' times, where 'n' is the length of the array, while the inner loop runs 'n-i-1' times, since the last 'i' elements are already in place. The 'if' statement checks if the current element is greater than the next element, and if so, swaps them using tuple unpacking. Finally, the sorted array is printed using a for loop.
原文地址: https://www.cveoy.top/t/topic/nHU5 著作权归作者所有。请勿转载和采集!