經典八種排序算法總結(帶動畫演示)

思惟導圖

文章已收錄Github精選,歡迎Star:https://github.com/yehongzhi/learningSummaryjava

前言

算法和數據結構是一個程序員的內功,因此常常在一些筆試中都會要求手寫一些簡單的排序算法,以此考驗面試者的編程水平。下面我就簡單介紹八種常見的排序算法,一塊兒學習一下。git

1、冒泡排序

思路:程序員

  • 比較相鄰的元素。若是第一個比第二個大,就交換它們兩個;
  • 對每一對相鄰元素做一樣的工做,從開始第一對到結尾的最後一對,這樣在最後的元素就是最大的數;
  • 排除最大的數,接着下一輪繼續相同的操做,肯定第二大的數...
  • 重複步驟1-3,直到排序完成。

動畫演示:github

實現代碼:
web

/**
 * @author Ye Hongzhi 公衆號:java技術愛好者
 * @name BubbleSort
 * @date 2020-09-05 21:38
 **/

public class BubbleSort extends BaseSort {
    
    public static void main(String[] args) {
        BubbleSort sort = new BubbleSort();
        sort.printNums();
    }
    
    @Override
    protected void sort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = 0; j < nums.length - i - 1; j++) {
                if (nums[j] > nums[j + 1]) {
                    int temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
            }
        }
    }
}
//10萬個數的數組,耗時:21554毫秒

平均時間複雜度:O(n²)面試

空間複雜度:O(1)算法

算法穩定性:穩定編程

2、插入排序

思路:數組

  1. 從第一個元素開始,該元素能夠認爲已經被排序;微信

  2. 取出下一個元素,在前面已排序的元素序列中,從後向前掃描;

  3. 若是該元素(已排序)大於新元素,將該元素移到下一位置;

  4. 重複步驟3,直到找到已排序的元素小於或者等於新元素的位置;

  5. 將新元素插入到該位置後;

  6. 重複步驟2~5。

動畫演示:

實現代碼:

/**
 * @author Ye Hongzhi 公衆號:java技術愛好者
 * @name InsertSort
 * @date 2020-09-05 22:34
 **/

public class InsertSort extends BaseSort {
    public static void main(String[] args) {
        BaseSort sort = new InsertSort();
        sort.printNums();
    }
    @Override
    protected void sort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        for (int i = 0; i < nums.length - 1; i++) {
            //當前值
            int curr = nums[i + 1];
            //上一個數的指針
            int preIndex = i;
            //在數組中找到一個比當前遍歷的數小的第一個數
            while (preIndex >= 0 && curr < nums[preIndex]) {
                //把比當前遍歷的數大的數字日後移動
                nums[preIndex + 1] = nums[preIndex];
                //須要插入的數的下標往前移動
                preIndex--;
            }
            //插入到這個數的後面
            nums[preIndex + 1] = curr;
        }
    }
}
//10萬個數的數組,耗時:2051毫秒

平均時間複雜度:O(n²)

空間複雜度:O(1)

算法穩定性:穩定

3、選擇排序

思路:

第一輪,找到最小的元素,和數組第一個數交換位置。

第二輪,找到第二小的元素,和數組第二個數交換位置...

直到最後一個元素,排序完成。

動畫演示:

實現代碼:

/**
 * @author Ye Hongzhi 公衆號:java技術愛好者
 * @name SelectSort
 * @date 2020-09-06 22:27
 **/

public class SelectSort extends BaseSort {
    public static void main(String[] args) {
        SelectSort sort = new SelectSort();
        sort.printNums();
    }
    @Override
    protected void sort(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            int minIndex = i;
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] < nums[minIndex]) {
                    minIndex = j;
                }
            }
            if (minIndex != i) {
                int temp = nums[i];
                nums[minIndex] = temp;
                nums[i] = nums[minIndex];
            }
        }
    }
}
//10萬個數的數組,耗時:8492毫秒

平均時間複雜度:O(n²)

算法空間複雜度:O(1)

算法穩定性:不穩定

4、希爾排序

思路:

把數組分割成若干(h)個小組(通常數組長度length/2),而後對每個小組分別進行插入排序。每一輪分割的數組的個數逐步縮小,h/2->h/4->h/8,而且進行排序,保證有序。當h=1時,則數組排序完成。

動畫演示:

實現代碼:

/**
 * @author Ye Hongzhi 公衆號:java技術愛好者
 * @name SelectSort
 * @date 2020-09-06 22:27
 **/

public class ShellSort extends BaseSort {

    public static void main(String[] args) {
        ShellSort sort = new ShellSort();
        sort.printNums();
    }

    @Override
    protected void sort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        int length = nums.length;
        int temp;
        //步長
        int gap = length / 2;
        while (gap > 0) {
            for (int i = gap; i < length; i++) {
                temp = nums[i];
                int preIndex = i - gap;
                while (preIndex >= 0 && nums[preIndex] > temp) {
                    nums[preIndex + gap] = nums[preIndex];
                    preIndex -= gap;
                }
                nums[preIndex + gap] = temp;
            }
            gap /= 2;
        }
    }
}
//10萬個數的數組,耗時:261毫秒

平均時間複雜度:O(nlog2n)

算法空間複雜度:O(1)

算法穩定性:穩定

5、快速排序

快排,面試最喜歡問的排序算法。這是運用分治法的一種排序算法。

思路:

  1. 從數組中選一個數作爲基準值,通常選第一個數,或者最後一個數。
  2. 採用雙指針(頭尾兩端)遍歷,從左往右找到比基準值大的第一個數,從右往左找到比基準值小的第一個數,交換兩數位置,直到頭尾指針相等或頭指針大於尾指針,把基準值與頭指針的數交換。這樣一輪以後,左邊的數就比基準值小,右邊的數就比基準值大。
  3. 對左邊的數列,重複上面1,2步驟。對右邊重複1,2步驟。
  4. 左右兩邊數列遞歸結束後,排序完成。

動畫演示:

實現代碼:

/**
 * @author Ye Hongzhi 公衆號:java技術愛好者
 * @name SelectSort
 * @date 2020-09-06 22:27
 **/

public class QuickSort extends BaseSort {

    public static void main(String[] args) {
        QuickSort sort = new QuickSort();
        sort.printNums();
    }

    @Override
    protected void sort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        quickSort(nums, 0, nums.length - 1);
    }

    private void quickSort(int[] nums, int star, int end) {
        if (star > end) {
            return;
        }
        int i = star;
        int j = end;
        int key = nums[star];
        while (i < j) {
            while (i < j && nums[j] > key) {
                j--;
            }
            while (i < j && nums[i] <= key) {
                i++;
            }
            if (i < j) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
        }
        nums[star] = nums[i];
        nums[i] = key;
        quickSort(nums, star, i - 1);
        quickSort(nums, i + 1, end);
    }
}
//10萬個數的數組,耗時:50毫秒

平均時間複雜度:O(nlogn)

算法空間複雜度:O(1)

算法穩定性:不穩定

6、歸併排序

歸併排序是採用分治法的典型應用,並且是一種穩定的排序方式,不過須要使用到額外的空間。

思路:

  1. 把數組不斷劃分紅子序列,劃成長度只有2或者1的子序列。
  2. 而後利用臨時數組,對子序列進行排序,合併,再把臨時數組的值複製回原數組。
  3. 反覆操做1~2步驟,直到排序完成。

歸併排序的優勢在於最好狀況和最壞的狀況的時間複雜度都是O(nlogn),因此是比較穩定的排序方式。

動畫演示:

實現代碼:

/**
 * @author Ye Hongzhi 公衆號:java技術愛好者
 * @name MergeSort
 * @date 2020-09-08 23:30
 **/

public class MergeSort extends BaseSort {

    public static void main(String[] args) {
        MergeSort sort = new MergeSort();
        sort.printNums();
    }

    @Override
    protected void sort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        //歸併排序
        mergeSort(0, nums.length - 1, nums, new int[nums.length]);
    }

    private void mergeSort(int star, int end, int[] nums, int[] temp) {
        //遞歸終止條件
        if (star >= end) {
            return;
        }
        int mid = star + (end - star) / 2;
        //左邊進行歸併排序
        mergeSort(star, mid, nums, temp);
        //右邊進行歸併排序
        mergeSort(mid + 1, end, nums, temp);
        //合併左右
        merge(star, end, mid, nums, temp);
    }

    private void merge(int star, int end, int mid, int[] nums, int[] temp) {
        int index = 0;
        int i = star;
        int j = mid + 1;
        while (i <= mid && j <= end) {
            if (nums[i] > nums[j]) {
                temp[index++] = nums[j++];
            } else {
                temp[index++] = nums[i++];
            }
        }
        while (i <= mid) {
            temp[index++] = nums[i++];
        }
        while (j <= end) {
            temp[index++] = nums[j++];
        }
        //把臨時數組中已排序的數複製到nums數組中
        if (index >= 0) System.arraycopy(temp, 0, nums, star, index);
    }
}
//10萬個數的數組,耗時:26毫秒

平均時間複雜度:O(nlogn)

算法空間複雜度:O(n)

算法穩定性:穩定

7、堆排序

大頂堆概念:每一個節點的值都大於或者等於它的左右子節點的值,因此頂點的數就是最大值。

思路:

  1. 對原數組構建成大頂堆。
  2. 交換頭尾值,尾指針索引減一,固定最大值。
  3. 從新構建大頂堆。
  4. 重複步驟2~3,直到最後一個元素,排序完成。

構建大頂堆的思路,能夠看代碼註釋。

動畫演示:

實現代碼:

/**
 * @author Ye Hongzhi 公衆號:java技術愛好者
 * @name HeapSort
 * @date 2020-09-08 23:34
 **/

public class HeapSort extends BaseSort {

    public static void main(String[] args) {
        HeapSort sort = new HeapSort();
        sort.printNums();
    }

    @Override
    protected void sort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        heapSort(nums);
    }

    private void heapSort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        //構建大根堆
        createTopHeap(nums);
        int size = nums.length;
        while (size > 1) {
            //大根堆的交換頭尾值,固定最大值在末尾
            swap(nums, 0, size - 1);
            //末尾的索引值往左減1
            size--;
            //從新構建大根堆
            updateHeap(nums, size);
        }
    }

    private void createTopHeap(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            //當前插入的索引
            int currIndex = i;
            //父節點的索引
            int parentIndex = (currIndex - 1) / 2;
            //若是當前遍歷的值比父節點大的話,就交換值。而後繼續往上層比較
            while (nums[currIndex] > nums[parentIndex]) {
                //交換當前遍歷的值與父節點的值
                swap(nums, currIndex, parentIndex);
                //把父節點的索引指向當前遍歷的索引
                currIndex = parentIndex;
                //往上計算父節點索引
                parentIndex = (currIndex - 1) / 2;
            }
        }
    }

    private void updateHeap(int[] nums, int size) {
        int index = 0;
        //左節點索引
        int left = 2 * index + 1;
        //右節點索引
        int right = 2 * index + 2;
        while (left < size) {
            //最大值的索引
            int largestIndex;
            //若是右節點大於左節點,則最大值索引指向右子節點索引
            if (right < size && nums[left] < nums[right]) {
                largestIndex = right;
            } else {
                largestIndex = left;
            }
            //若是父節點大於最大值,則把父節點索引指向最大值索引
            if (nums[index] > nums[largestIndex]) {
                largestIndex = index;
            }
            //若是父節點索引指向最大值索引,證實已是大根堆,退出循環
            if (largestIndex == index) {
                break;
            }
            //若是不是大根堆,則交換父節點的值
            swap(nums, largestIndex, index);
            //把最大值的索引變成父節點索引
            index = largestIndex;
            //從新計算左節點索引
            left = 2 * index + 1;
            //從新計算右節點索引
            right = 2 * index + 2;
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
//10萬個數的數組,耗時:38毫秒

平均時間複雜度:O(nlogn)

算法空間複雜度:O(1)

算法穩定性:不穩定

8、桶排序

思路:

  1. 找出最大值,最小值。
  2. 根據數組的長度,建立出若干個桶。
  3. 遍歷數組的元素,根據元素的值放入到對應的桶中。
  4. 對每一個桶的元素進行排序(可以使用快排,插入排序等)。
  5. 按順序合併每一個桶的元素,排序完成。

對於數組中的元素分佈均勻的狀況,排序效率較高。相反的,若是分佈不均勻,則會致使大部分的數落入到同一個桶中,使效率下降。

動畫演示(來源於五分鐘學算法,侵刪):

實現代碼:

/**
 * @author Ye Hongzhi 公衆號:java技術愛好者
 * @name BucketSort
 * @date 2020-09-08 23:37
 **/

public class BucketSort extends BaseSort {

    public static void main(String[] args) {
        BucketSort sort = new BucketSort();
        sort.printNums();
    }

    @Override
    protected void sort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        bucketSort(nums);
    }

    public void bucketSort(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }
        //找出最大值,最小值
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int num : nums) {
            min = Math.min(min, num);
            max = Math.max(max, num);
        }
        int length = nums.length;
        //桶的數量
        int bucketCount = (max - min) / length + 1;
        int[][] bucketArrays = new int[bucketCount][];
        //遍歷數組,放入桶內
        for (int i = 0; i < length; i++) {
            //找到桶的下標
            int index = (nums[i] - min) / length;
            //添加到指定下標的桶裏,而且使用插入排序排序
            bucketArrays[index] = insertSortArrays(bucketArrays[index], nums[i]);
        }
        int k = 0;
        //合併所有桶的
        for (int[] bucketArray : bucketArrays) {
            if (bucketArray == null || bucketArray.length == 0) {
                continue;
            }
            for (int i : bucketArray) {
                //把值放回到nums數組中
                nums[k++] = i;
            }
        }
    }

    //每一個桶使用插入排序進行排序
    private int[] insertSortArrays(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return new int[]{num};
        }
        //建立一個temp數組,長度是arr數組的長度+1
        int[] temp = new int[arr.length + 1];
        //把傳進來的arr數組,複製到temp數組
        for (int i = 0; i < arr.length; i++) {
            temp[i] = arr[i];
        }
        //找到一個位置,插入,造成新的有序的數組
        int i;
        for (i = temp.length - 2; i >= 0 && temp[i] > num; i--) {
            temp[i + 1] = temp[i];
        }
        //插入須要添加的值
        temp[i + 1] = num;
        //返回
        return temp;
    }
}
//10萬個數的數組,耗時:8750毫秒

平均時間複雜度:O(M+N)

算法空間複雜度:O(M+N)

算法穩定性:穩定(取決於桶內的排序算法,這裏使用的是插入排序因此是穩定的)。

總結

動畫演示來源於算法學習網站:https://visualgo.net

講完這些排序算法後,可能有人會問學這些排序算法有什麼用呢,難道就爲了應付筆試面試?平時開發也沒用得上這些。

我以爲咱們應該換個角度來看,好比高中時咱們學物理,化學,數學,那麼多公式定理,如今也沒怎麼用得上,可是高中課本爲何要教這些呢?

個人理解是:第一,普及一些常識性的問題。第二,鍛鍊思惟,提升解決問題的能力。第三,爲了區分人才。

回到學排序算法有什麼用的問題上,實際上也同樣。這些最基本的排序算法就是一些常識性的問題,做爲開發者應該瞭解掌握。同時也鍛鍊了編程思惟,其中包含有雙指針,分治,遞歸等等的思想。最後在面試中體現出來的就是人才的劃分,懂得這些基本的排序算法固然要比不懂的人要更有競爭力。

建議你們看完以後,能找時間動手寫一下,加深理解。

上面全部例子的代碼都上傳Github了:

https://github.com/yehongzhi/mall

以爲有用就點個贊吧,你的點贊是我創做的最大動力~

拒絕作一條鹹魚,我是一個努力讓你們記住的程序員。咱們下期再見!!!

能力有限,若是有什麼錯誤或者不當之處,請你們批評指正,一塊兒學習交流!

本文分享自微信公衆號 - java技術愛好者(yehongzhi_java)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索