An algorithm with a bad reputation (2) - bubble sort algorithm

Please indicate the source when reprinting, thank you!

The idea of ​​bubble sort algorithm:

  • The sequence of records is scanned from bottom to top (or top to bottom), and two adjacent records are swapped Riwith Ri-1(or ) if they are in reverse order.Ri+1

exchange sort

  • Bubble Sort
  • quicksort

Algorithm Description

  • A notorious algorithm
  • Sorting is stable

ArrayList implementation:

import java.util.ArrayList;
import java.util.Random;

public class Bubble {
    public static void sort(ArrayList<Integer> al) {
        int n = al.size();
        for (int i = n - 1; i >= 0; i--) {
            boolean flag = false;//若不发生交换了,以便提前结束算法。
            for (int j = i ; j > 0; j--) {
                if (al.get(j) < al.get(j-1)) {
                    Integer tempInt = al.get(j);
                    al.set(j, al.get(j-1));
                    al.set(j-1, tempInt);
                    flag = true;
                }
            }
            System.out.println(al);
            if (!flag)
                break;
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int n = 10;
        ArrayList<Integer> al = new ArrayList<>(n);
        // 创建一个随机数生成器
        Random rand = new Random();
        // 添加1-100的随机整数

        for (int i = 0; i < n; i++) {
            al.add(new Integer(Math.abs(rand.nextInt(100)) + 1));
        }
        System.out.println("The ArrayList Sort Before:\n" + al + "\nsorting:");
        Bubble.sort(al);
    }

}

Output:

The ArrayList Sort Before:
[39, 7, 8, 77, 61, 6, 3, 50, 81, 85]
sorting:
[3, 39, 7, 8, 77, 61, 6, 50, 81, 85]
[3, 6, 39, 7, 8, 77, 61, 50, 81, 85]
[3, 6, 7, 39, 8, 50, 77, 61, 81, 85]
[3, 6, 7, 8, 39, 50, 77, 61, 81, 85]
[3, 6, 7, 8, 39, 50, 77, 61, 81, 85]

——@guoyangde http://www.cnblogs.com/LittleTreasureBox/p/8904016.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324649963&siteId=291194637