Python 程序的冒泡排序
在本文中,我们将学习冒泡排序排序技术的实现。
下图说明了此算法的工作原理 −
方式
从第一个元素(索引 = 0)开始,将当前元素与数组的下一个元素进行比较。
如果当前元素大于数组的下一个元素,则交换它们。
如果当前元素小于下一个元素,则移动到下一个元素。
重复步骤 1。
现在让我们看看下面的实现 −
示例
def bubbleSort(ar): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in correct position for j in range(0, n-i-1): # Swap if the element found is greater than the next element if ar[j] > ar[j+1] : ar[j], ar[j+1] = ar[j+1], ar[j] # Driver code to test above ar = ['t','u','t','o','r','i','a','l'] bubbleSort(ar) print ("Sorted array is:") for i in range(len(ar)): print (ar[i])
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
Sorted array is: a i o r t t u l
结论
在本文中,我们学习了在 Python 3.x 中执行冒泡排序的方式。或更早
广告