• 常见排序算法概述


    一、算法复杂度对比

      总之,

      在平均情况下,快速排序最快;

      在最好情况下,冒泡排序和直接插入排序最快;

      在最坏情况下,堆排序和归并排序排序速断最快。

      常见的算法时间复杂度由小到大依次为:

      O(1)<O(log2n)<O(n)<O(nlog2n)<O(n2)<O(n3)<…<O(2n)<O(n!)

    二、排序算法说明

            1. 冒泡排序

        运作如下:

                 a. 比较相邻元素,如果前一个比后一个大,就把它们调换位置

          b. 对每一对相邻的元素做同样的工作,从开始第一对到结束最后一对。这步做完,最后的元素就是最大的元素

                 c. 针对所有元素重复以上的步骤,除了最后一个

                 d. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

                 口诀:  外层循环n-1,内层循环n-1-i.

                 例子:

                  

     1 public static void main(String[] args) {
     2         int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
     3         SortCommon.bubbleSort(arr);
     4  }
     5 
     6  public static void bubbleSort(int[] arr) {
     7         boolean didSwap;
     8         for (int i = 0; i < arr.length - 1; i++) {
     9             didSwap = false;
    10             for (int j = 0; j < arr.length - 1 - i; j++) {
    11                 if (arr[j] > arr[j + 1]) {
    12                     swap(arr, j, j + 1);
    13                     didSwap = true;
    14                 }
    15             }
    16 
    17             if (didSwap == false) {
    18                 break;
    19             }
    20 
    21             System.out.println(Arrays.toString(arr));
    22 
    23         }
    24 
    25     }
    26 
    27     private static void swap(int[] arr, int index1, int index2) {
    28         int tempValue = arr[index1];
    29         arr[index1] = arr[index2];
    30         arr[index2] = tempValue;
    31     }

    // 排序执行结果

    [8, 7, 6, 5, 4, 3, 2, 1, 0, 9]
    [7, 6, 5, 4, 3, 2, 1, 0, 8, 9]
    [6, 5, 4, 3, 2, 1, 0, 7, 8, 9]
    [5, 4, 3, 2, 1, 0, 6, 7, 8, 9]
    [4, 3, 2, 1, 0, 5, 6, 7, 8, 9]
    [3, 2, 1, 0, 4, 5, 6, 7, 8, 9]
    [2, 1, 0, 3, 4, 5, 6, 7, 8, 9]
    [1, 0, 2, 3, 4, 5, 6, 7, 8, 9]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    1.  快速排序

    2.  直接插入排序

    3.  shell排序

    4.  直接选择

    5.  堆排序

    6.  归并排序

    7.  基数排序

    齊帥
  • 相关阅读:
    JQuery:自动触发事件
    SQL Server 取日期时间部分
    使用IIS 7.0 / 7.5 时配置HttpModules需要注意
    Winform:中直接打开指定文件
    jQuery 时间获取扩展
    喵星史话(一)——猫的起源
    2013年的环法
    ie8下奇怪的问题:float:left之后,右侧的div会影响左侧
    虚假IP和DNS污染
    android中setBackgroundResource和setBackgroundDrawable和用法
  • 原文地址:https://www.cnblogs.com/qishuai/p/6479290.html
Copyright © 2020-2023  润新知