Java排序算法

Posted by 瞿广 on Saturday, August 17, 2019

TOC

总结简单的排序算法

有个不错的网站,动画演示各种算法:visualgo

冒泡排序

10import java.util.Arrays;
11
12public class BubbleSort {
13
14    static int[] array = {1, 4, 2, 8, 20, 23, 12};
15
16    public static void main(String[] args) {
17        int[] b = sort(array);
18        System.out.println(Arrays.toString(b));
19    }
20
21    public static int[] sort(int[] array) {
22        int n = array.length;
23        boolean flag = false;
24        for (int i = 0; i < n; i++) {
25            int s = n - i - 1;
26            System.out.println(s);
27            for (int j = 0; j < s; j++) {
28                if (array[j] > array[j + 1]) {
29                    int tmp = array[j];
30                    array[j] = array[j + 1];
31                    array[j + 1] = tmp;
32                    flag = true;
33                }
34            }
35            if (!flag) {
36                break;
37            }
38        }
39        return array;
40    }
41}

插入排序

package com.techqu.sort;

import java.util.Arrays;

public class InsertSort {

    static int[] array = {1, 4, 2, 8, 20, 23, 12};

    public static void main(String[] args) {
        int[] b = sort(array);
        System.out.println(Arrays.toString(b));

    }

    public static int[] sort(int[] array) {
        int n = array.length;
        for (int i = 1; i < n; i++) {
            int value = array[i];
            int j = i - 1;
            for (; j > 0; j--) {
                if (value < array[j]) {
                    array[j + 1] = array[j];//数据移动
                } else {

                    break;
                }
            }
            array[j + 1] = value;//插入数据
        }
        return array;
    }
}

选择排序

package com.techqu.sort;

import java.util.Arrays;

public class SelectSort {

    static int[] array = {1, 4, 2, 8, 20, 23, 12};

    public static void main(String[] args) {

        int[] b = sort(array);
        System.out.println(Arrays.toString(b));

    }

    public static int[] sort(int[] array) {
        int n = array.length;

        for (int i = 0; i < n - 1; i++) {
            System.out.println(Arrays.toString(array));
            int min_index = i;
            for (int j = i + 1; j < n; j++) {

                System.out.println(array[min_index] + "," + array[j]);
                if (array[min_index] > array[j]) {
                    min_index = j;
                }

            }
            if (i != min_index) {
                int tmp = array[i];
                array[i] = array[min_index];
                array[min_index] = tmp;
            }

        }
        return array;

    }

}