排序算法合辑

常见排序算法及实现(Java)如下:

  1. 冒泡排序
  2. 选择排序
  3. 插入排序
  4. 希尔排序
  5. 归并排序
  6. 快速排序
  7. 基数排序
  8. 堆排序
  9. 计数排序
  10. 桶排序

排序测试代码模板:

public class Test {

    public static void main(String[] args) {
        int[] data = getData();
        //排序开始
        
        //排序结束
        check(data);
    }

    private static int[] getData() {
        int length = 10;
        int max = 100;
        Random random = new Random();
        int[] data = new int[length];
        for (int i = 0; i < length; i++) {
            data[i] = random.nextInt(max);
        }
        print(data);
        return data;
    }

    private static void check(int[] data) {
        print(data);
        int asc = 0;
        int desc = 0;
        for (int i = 0; i < data.length - 1; i++) {
            if (data[i] < data[i + 1]) {
                asc++;
            } else if (data[i] > data[i + 1]) {
                desc++;
            } else {
                asc++;
                desc++;
            }
        }
        if (asc == data.length - 1 && desc != data.length - 1) {
            System.out.println("升序");
        } else if (asc != data.length - 1 && desc == data.length - 1) {
            System.out.println("降序");
        } else {
            System.out.println("检测不通过");
        }
    }

    private static void print(int[] data) {
        for (int i = 0; i < data.length; i++) {
            System.out.print(data[i] + " ");
        }
        System.out.println();
    }

}

相关文章