冒泡排序最好的时间复杂度是O(n)。反之,最坏情况下为O(n2)。
冒泡排序是就地排序,且它是稳定的。第一趟得到的最后位置上的关键字一定是最大的或者最小的。
冒泡排序是一种比较简单的排序
java代码:
public class BubbleSort { public static void main(String[] args) { int array[] = {5, 18, 151, 138, 160, 63, 174, 169, 79, 200}; showArray(array); System.out.println("\n排序后"); bubbleSort(array); showArray(array); } private static void swap(int[] arr,int a,int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static void bubbleSort(int[] a) { int len = a.length; for(int i=1;i<len;i++) { for(int j=0;j<len-i;j++) { if(a[j]>a[j+1]) swap(a,j,j+1); } } } private static void showArray(int[] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } }
C代码:
#include<stdio.h> #include<malloc.h> void showArray(int a[],int len){ for(int i=0;i<len;i++){ printf("%d ",a[i]); } } void swap(int* a,int *b) { int temp = *a; *a = *b; *b = temp; } void bubbleSort(int a[],int len) { for(int i=1;i<len;i++) { for(int j=0;j<len-i;j++) { if(a[j]>a[j+1]) swap(&a[j],&a[j+1]); } } } int main() { int a[] = {5, 18, 151, 138, 160, 63, 174, 169, 79, 200}; int len = sizeof(a)/sizeof(int); showArray(a,len); bubbleSort(a,len); printf("\n排序后:\n"); showArray(a,len); return 0; }