java数据结构排序之冒泡排序

冒泡排序

基本思想

  • 通过比较相邻的关键字间的大小,来对相应关键字的顺序进行交换,每趟排序都能找出最大或者最小的关键字放在数组末尾。

在这里插入图片描述

/**
* Created by 胡歌的小迷弟 on 2019/9/25 16:12
*/
public class Maopaosort {

   public static void main(String[] args) {
       int a[]={79,56,90,432,27,16,88,35};
       sort(a);
       for(int i=0;i<a.length;i++){
           System.out.println(a[i]);
       }

   }

   static  int temp=0;
   public static void sort(int a[]){
       for(int i=0;i<a.length;i++){
           for(int j=0;j<a.length-i-1;j++){
               if(a[j]>a[j+1]){
                   temp=a[j];
                   a[j]=a[j+1];
                   a[j+1]=temp;
               }
           }
       }
   }
}

冒泡排序的小优化

/**
* Created by 胡歌的小迷弟 on 2019/9/25 16:12
*/
public class Maopaosort {

   public static void main(String[] args) {
       int a[]={3,9,-1,10,-2};
       sort(a);
       for(int i=0;i<a.length;i++){
           System.out.println(a[i]);
       }

   }

   boolean flag=false; //判断当前循环是否有交换
   static  int temp=0;
   public static void sort(int a[]){
       for(int i=0;i<a.length;i++){
           for(int j=0;j<a.length-i-1;j++){
               if(a[j]>a[j+1]){
                   flag=true;
                   temp=a[j];
                   a[j]=a[j+1];
                   a[j+1]=temp;
               }
           }
           if(!flag){
               break;//在一次交换中没有一次交换发生过
           }else{
               flag=false;//重置flag,进行下次判断
           }
       }
   }
}

发布了40 篇原创文章 · 获赞 6 · 访问量 1456

猜你喜欢

转载自blog.csdn.net/qq_26737667/article/details/102873379
今日推荐