冒泡排序和优化

冒泡思想:两两比较相邻记录,内循环将最小的数通过交换浮上来。

优化思想:设置flag,对已经有序的序列就不继续判断了

冒泡排序的实现:

package Bubble_Sort;

//冒泡算法和改进算法,正序,从小到大(从1开始)
public class BubbleSort {

    public int[] a=new int[11];
    public int size;
    public int count;
    public boolean flag=true;
    
    public BubbleSort(int[] a)
    {
        for(int i=0;i<a.length;i++)
        {
            this.a[i+1]=a[i];
        }
        size=a.length;
    }
    //冒泡算法
    public void bubbleSort()
    {
        for(int i=1;i<size;i++)
        {
            for(int j=size;j>i;j--)
            {
                count++;
                if(a[j]<a[j-1])
                {
                    
                    int temp=a[j-1];
                    a[j-1]=a[j];
                    a[j]=temp;
                }
            }
        }
    }
    //冒泡改进算法
    public void bubbleSortImpro()
    {
        for(int i=1;i<size&&flag;i++)
        {
            flag=false;              
            for(int j=size;j>i;j--)
            {
                if(a[j]<a[j-1])
                {
                    count++;
                    swap(a, j, j-1);
                    flag=true;         //改变顺序则flag=False;
                }
            }
        }
    }
    public void traversal()
    {
        for(int i=1;i<=size;i++)
        {
            System.out.println(a[i]);
        }
    }
    public void swap(int[] arr,int a,int b)
    {
        arr[a] = arr[a]+arr[b];
        arr[b] = arr[a]-arr[b];
        arr[a] = arr[a]-arr[b];
    }
}

测试:

package Bubble_Sort;

public class App {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a={6,21,3,99,56,44,77,12,7,19};
        int[] b={2,1,3,4,5,6,7,8,9,10};
        BubbleSort bubbleSort=new BubbleSort(a);
//        bubbleSort.bubbleSortImpro();
        bubbleSort.bubbleSort();
        bubbleSort.traversal();
        System.out.println("j改变次数:"+bubbleSort.count);
    }
}

结果:

冒泡法
j改变次数:45

优化方法:
j改变次数:21

猜你喜欢

转载自www.cnblogs.com/siyyawu/p/10182514.html