冒泡排序法-个人学习

来源:互联网 发布:淘宝商学院在哪里 编辑:程序博客网 时间:2024/06/05 07:38
package com.sort;import java.util.Arrays;public class BubbleSort {    public static void main(String[] args) {        int[] list = {1,3,54,23,76,45,24};        bubble3(list);        System.out.println(Arrays.toString(list));    }    //小到大    public static void bubble1(int[] list){        int size = list.length;        for(int i = 0; i < size; i++){            for(int j = 1; j < size - i; j++){                if(list[j-1] < list[j]){                    int temp = list[j-1];                    list[j-1] = list[j];                    list[j] = temp;                }            }        }    }    //优化:若某一趟未发生交换,则说明后续无需继续冒泡    public static void bubble2(int[] list){        boolean flag = true;        int size = list.length;        while(flag){            flag =false;            for(int i = 1; i < size; i++){                if(list[i-1] > list[i]){                    int temp = list[i-1];                    list[i-1] = list[i];                    list[i] = temp;                    flag = true;                }            }            size --;        }    }    //优化:方法2的基础上新增上一趟替换位置标识,下一趟只需比较到上一趟的下标为止    public static void bubble3(int[] list){        boolean flag = true;        int size = list.length;        while(flag){            flag =false;            for(int i = 1; i < size; i++){                if(list[i-1] > list[i]){                    int temp = list[i-1];                    list[i-1] = list[i];                    list[i] = temp;                    flag = true;                    size = i - 1;                }            }        }    }}