Java之三大基础排序(冒泡、选择、插入)

注:以下排序均为从小到大

一、冒泡排序

package com.yunche.testsort;

import java.util.Arrays;

/**
 * @ClassName: BubbleSort
 * @Description:
 * @author: yunche
 * @date: 2018/11/30
 */
public class BubbleSort {
    public static void main(String[] args) {
        int[] a = {1, 7, 3, 3, 5, 4, 6, 2, 8};
        new BubbleSort().sort(a);
        System.out.println(Arrays.toString(a));
    }/*Output:
    [1, 2, 3, 3, 4, 5, 6, 7, 8]
    */
    
    private void sort(int[] a) {
        int len = a.length;
        for (int i = 0; i < len - 1; i++) {
            for (int j = 0; j < len - i - 1; j++) {
                //swap
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
    }
}

二、选择排序

package com.yunche.testsort;

import java.util.Arrays;

/**
 * @ClassName: SelectionSort
 * @Description:
 * @author: yunche
 * @date: 2018/11/30
 */
public class SelectionSort {
    public static void main(String[] args) {
        int[] a = {2, 1, 3, 5, 3, 4, 10, 7, 6};
        new SelectionSort().sort(a);
        System.out.println(Arrays.toString(a));
    }/*
    Output:[1, 2, 3, 3, 4, 5, 6, 7, 10]
    */

    private void sort(int[] a) {
        int len = a.length;
        for (int i = 0; i < len - 1; i++) {
            //select max
            int index = 0;
            int j;
            for (j = 1; j < len - i; j++) {
                index = a[index] < a[j] ? j : index;
            }
            //swap
            int temp = a[index];
            a[index] = a[j - 1];
            a[j - 1] = temp;
        }
    }

}

三、插入排序

package com.yunche.testsort;

import java.util.Arrays;

/**
 * @ClassName: InsertionSort
 * @Description:
 * @author: yunche
 * @date: 2018/11/30
 */
public class InsertionSort {
    public static void main(String[] args) {
        int[] a = {2, 1, 3, 1, 7, 4, 5, 3, 8, 6};
        new InsertionSort().sort(a);
        System.out.println(Arrays.toString(a));
    }/*
    Output:[1, 1, 2, 3, 3, 4, 5, 6, 7, 8]
    */

    private void sort(int[] a) {
        //将当前元素插入到左侧已经排好序的数组中,使之依然有序
        int len = a.length;
        for (int i = 1; i < len; i++) {
            for (int j = i; j > 0; j--) {
                //使当前元素找到属于自己的位置
                if (a[j] < a[j - 1]) {
                    int temp = a[j];
                    a[j] = a[j - 1];
                    a[j - 1] = temp;
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/yunche/p/10042906.html