python使用冒泡排序对list列表进行排序_冒泡排序法|java、python冒泡排序实现代码...

冒泡排序算法思想:

让数组中的两个相邻数字进行比较,数组中较大的值向下沉,值小的上浮,就类似于水中的气泡,较大的下沉,较小的上升,慢慢冒出来。简单的说就是数值大的会慢慢往前排,数据值小的会慢慢向后排,最终实现由小到达排列,最小的排在最前,最大的排到最后。

冒泡排序图解:

1574231046596_冒泡排序算法执行前开始前.jpg

算法执行前

1574674127103_冒泡排序算法执行后.jpg

算法执行后

1574231078139_冒泡排序动图.gif

冒泡算法执行过程【动图版】

冒泡排序算法JAVA实现代码

import com.jiajia.ArrayUtil.*; // 按包名导入

public class BubbleSortMain {

public static void main(String[] args) {

int[] arr = {3,43,38,5,47,15,36,26,27,2,44,4,50,19,38};

bubbleSort(arr);

ArrayUtil.print(arr);

}

/**

* 冒泡排序

*/

private static void bubbleSort(int[] arr) {

for (int i = 0; i < arr.length; i++) {

for (int j = 0; j < arr.length - i -1; j++) { // 这里说明为什么需要-1

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

}

}

}

}

}

冒泡排序算法python实现代码

def bubble_sort(the_list):

i = 0

while i < len(the_list):

j = 0

while j < len(the_list)-1:

print(the_list[j],the_list[j+1])

if the_list[j] > the_list[j+1]:

the_list[j], the_list[j+1] = the_list[j+1], the_list[j]

j = j+1

print(the_list)

print("======"+str(the_list))

i = i+1

return the_list

if __name__ == '__main__':

the_list = [3, 43, 38, 5, 47, 15, 36, 26, 27, 2, 44, 4, 50, 19, 38]

print("排序前:" + str(the_list))

print("排序后:" + str(bubble_sort(the_list)))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值