1. 程式人生 > >Java之三大基礎排序(冒泡、選擇、插入)

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;
                }
            }
        }
    }
}