原理:临近的数字两两进行比较,按照从小到大或者从大到小的顺序进行交换,这样一趟过去后,最大或最小的数字被交换到了最后一位,然后再从头开始进行两两比较交换,直到倒数第二位时结束,以此类推。(第1次排序比较到最后1个数,第2次排序比较到倒数第3个数,第3次排序比较到倒数第3个数。。。。。)
实现(java):
public class BubbleSort {
public static void main(String[] args){
// TODO Auto-generated method stub
long[] arr={9,6,5,8,4,2,3,1,7};
try{
BubbleSort.bubbleSort(arr,"esc");
for(int i=0;i<arr.length;i++){
System.out.print(" "+arr[i]);
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* @param args
* array long类型数组
* sortType 排序类型 asc升序 desc降序
* @throws Exception
*/
public static void bubbleSort(long[] array,String sortType) throws Exception{
for(int i=array.length-1;i>0;i--){
for(int j=0;j<i;j++){
if(sortType!=null&&"asc".equals(sortType)){
if(array[j]>array[j+1]){
long temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}else if(sortType!=null&&"desc".equals(sortType)){
if(array[j]<array[j+1]){
long temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}else{
throw new Exception("排序类型不正确!");
}
}
}
}
}