1、基本思想
在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。即:每当两相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换。
2、代码示例
package sort; /** * 冒泡排序 */ public class BubbleSort { public void TestSort(){ int a[]={49,38,62,99,98,54,56,15,35,25,53,51}; sort(a); } public void sort(int arr[]){ int temp; int len=arr.length; 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 i=0;i<len;i++){ System.out.print(arr[i]+" "); } } }