# 数据结构与算法冒泡排序

## 本节我们说说常见的排序算法

 1 #c语言
2 #include <stdio.h>
3
4 int main() {
5     int array[] = {23,53,1,67,83,40};
6     int n =6;
7     for (int i = n-1; i >=1; i--) {
8         for (int j = 0; j < i; ++j) {
9             if (array[j]>array[j+1]){
10                 int t = array[j];
11                 array[j] = array[j+1];
12                 array[j+1] = t;
13             }
14         }
15     }
16     for (int i = 0; i < n; ++i) {
17         printf("%d,",array[i]);
18     }
19     return 0;
20 }
 1 #使用java实现
2 public static void bubble_sort(int[] arr) {
3         int i, j, temp, len = arr.length;
4         for (i = 0; i < len - 1; i++)
5             for (j = 0; j < len - 1 - i; j++)
6                 if (arr[j] > arr[j + 1]) {
7                     temp = arr[j];
8                     arr[j] = arr[j + 1];
9                     arr[j + 1] = temp;
10                 }

 1 # python
2 def bubble_sort(li):
3     for i in range(len(li)-1):
4         for j in range(len(li)-i-1):
5             if li[j] > li[j+1]:
6                 #两个数交换
7                 li[j] li[j+1] = li[j+1] li[J]
8         print(li)
9
10 li = [3,4,2,8,6,1]
11 print(li)
12 bunnle_sort(li)

 1 # python
2 def bubble_sort(li):
3     for i in range(len(li)-1):
4         exchange = False
5         for j in range(len(li)-i-1):
6             if li[j] > li[j+1]:
7                 #两个数交换
8                 li[j] li[j+1] = li[j+1] li[J]
9                 #数交换则执行True
10                 exchange = Ture
11         print(li)
12         if not exchange:
13             return
14
15 li = [3,4,2,8,6,1]
16 print(li)
17 bunnle_sort(li)

posted @ 2019-10-25 22:02  xbhog  阅读(794)  评论(0编辑  收藏  举报