(1)比较两个相邻的元素。如果第一个元素比第二个元素大,就进行交换;
(2)从第一对到最后一对进行比较,比较完成后最后一位元素应该会是最大的数;
(3)对除了最后一个元素以外的元素重复步骤1~2,直到排序完成。
#include <stdio.h> void bubble_sort(int arr[], int len); void main() { int arr[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; int len = (int) sizeof(arr) / sizeof(arr[0]); bubble_sort(arr, len); } void bubble_sort(int arr[], int len){ int i, j, temp; for (i = 0; i < len - 1; i++){ for (j = 0; j < len - 1 - i; j++){ if (arr[j] > arr[j + 1]){ temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } for (int k = 0; k < len; k++){ printf("%-3d ", arr[k]); } printf("\n"); } }
class bubbleSort{ public static void main(String[] args) { int arr[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; int len = arr.length; bubble_sort(arr, len); } public static void bubble_sort(int[] arr, int len) { int temp; for (int i = 0; i < len - 1; i++){ for (int j = 0; j < len - 1 - i; j++){ if (arr[j] > arr[j + 1]){ temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } for (int k = 0; k < len; k++){ System.out.print(arr[k]+" "); } System.out.println(); } } }
arr = [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ] len = len(arr) for i in range (0,len - 1): for j in range(0,len - 1 - i): if arr[j] > arr[j + 1]: temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp for k in range(0,len): print(arr[k],end = " ") print()