YouTip LogoYouTip

Python Bubble Sort

# Python3.x Python Bubble Sort [![Image 4: Document Object Reference](#) Python3 Examples](#) Bubble sort is a simple **exchange sorting algorithm**, whose core working principle is: 1. Repeatedly traverse the list to be sorted, comparing **two adjacent elements** at a time; 2. If the order of the two elements does not meet the requirements (for example, in ascending order, the previous element is greater than the next one), **swap their positions**; 3. Each traversal will **bubble the largest element** in the current unsorted part to the end (in the ascending scenario), just like a bubble rising to the surface; 4. Repeat the above process until the entire list is completely sorted (no swap operations occur or all elements have been traversed). !(#) ### Key Characteristics * Sorting Type: Exchange Sort * Time Complexity: Worst Case / O(nΒ²) (list completely reversed), Average Case / O(nΒ²), Best Case / O(n) (optimized version, list already sorted) * Space Complexity: O(1) (in-place sorting, no extra auxiliary space needed) * Stability: Stable Sort (the relative order of equal elements does not change) ## Example def bubbleSort(arr): n = len(arr)# Traverse all array elements for i in range(n): # The last i elements are already in the correct position (no need to compare again)for j in range(0, n-i-1): if arr>arr[j+1] : arr, arr[j+1] = arr[j+1], arrarr = [64, 34, 25, 12, 22, 11, 90]bubbleSort(arr)print("Sorted array:")for i in range(len(arr)): print("%d" %arr), Executing the above code outputs the following result: Sorted array:11122225346490 [![Image 6: Document Object Reference](#) Python3 Examples](#)
← Method TowerMethod Overloading β†’