[The Java] sorting algorithm> A Sorting> [a bubble sort] (O (N * N) / stabilizing / N smaller / order / sequence + chain)

1 bubble sort

1.1 ALGORITHM

The basic idea of ​​the sort of exchange: pairwise comparison of records to be sorted key, if it is found two record does not meet the requirements of the order, then: exchange until the entire sequence all meet the requirement.

1.2 algorithm feature

  • [Belong] Sort exchange
  • Suitable for Stability []: stability
  • [N] applies to the size: small
  • Suitable for [ordering]: Ordered
  • Suitable [Storage Structure: sequential storage or storage chain (both available)
  • Related formulas: [insert time] to take bunching good order, [insert] to take a small number of records, [insert] N party to take a second election

1.3 Algorithm

import java.util.Arrays;

public class BubbleSort {
    public static int [] bubbleSort(int []array){
        int [] resultArray = Arrays.copyOfRange(array, 0, array.length);

        for(int i=0;i<array.length-1;i++){//趟数
            for(int j=0;j<array.length-1-i;j++){//每一趟内,进行相邻元素的比较:将较大值元素向后移动
                if(resultArray[j]>resultArray[j+1]){
                    int tmp = resultArray[j];
                    resultArray[j] = resultArray[j+1];
                    resultArray[j+1] = tmp;
                }
            }
        }
        return resultArray;
    }
}

1.4 test implementation

import java.util.Scanner;

public class Main {
    public static void print(int[] array){
        if(array==null || array.length<1){
            return;
        }
        for(int i=0;i<array.length-1;i++){
            System.out.print(array[i]+" ");
        }
        System.out.println(array[array.length-1]);
    }

    public static void main(String[] args) {
        //1 输入 一组 乱序的数值 数组
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        String [] strValues = input.trim().split(" ");
        int [] array = new int[strValues.length];
        for(int i=0,len=strValues.length;i<len;i++){
            array[i] = Integer.valueOf(strValues[i]).intValue();//假定所有输入均为合规的整型数值
        }
//        print(array);// test - 输出 所输入的数据

        //2 排序
        int [] sortedArray = BubbleSort.bubbleSort(array);
        //3 输出
        print(sortedArray);
    }
}
//input↓
3 6 5 8 9 4 2 7
//output↓
2 3 4 5 6 7 8 9

1.5 References

  • "Data structure (C language - 2nd Edition - Yan Wei-Min Wu Weimin forward)": Page241

Guess you like

Origin www.cnblogs.com/johnnyzen/p/12436117.html