插入排序的實現與優化並和選擇排序進行效能比較

2021-09-01 03:05:52 字數 2231 閱讀 4826

插入排序

第一種:交換法

| 8 | 6 | 3 | 2 | 10 | 9 | 11 | 4 | 5 |

第乙個元素就不需要考慮了,直接看第二個元素6,因為6<8,所以6與8交換位置得到:

| 6 | 8 | 3 | 2 | 10 | 9 | 11 | 4 | 5 |

在考慮第三個元素3,因為3<8,交換3和8,再比較3和6因為3<6,交換3和6得到:

| 3 | 6 | 8 | 2 | 10 | 9 | 11 | 4 | 5 |

後面以此類推

第二種:複製法:

|51|6|85|6|8|5|4|

| | 6|

將6複製乙份,然後比較6之前的元素51

因為6<51,不適合放到當前位置,所以將51向後移動 ,考慮6是不是應該放到前乙個位置

|51|51|85|6|8|5|4|

|6 |

因為現在6已經是第0個位置了,所以就放到這個位置。。。。以此類推

和上乙個部落格一樣,將之前的選擇排序寫到乙個 .h 檔案中來測試:

測試**:

#ifndef inc_04_insertion_sort_sorttesthelper_h

#define inc_04_insertion_sort_sorttesthelper_h

#include #include #include #include #include using namespace std;

namespace sorttesthelper

// 拷貝整型陣列a中的所有元素到乙個新的陣列, 並返回新的陣列

int *copyintarray(int a, int n)

// 列印arr陣列的所有內容

templatevoid printarray(t arr, int n)

// 判斷arr陣列是否有序

templatebool issorted(t arr, int n)

// 測試sort排序演算法排序arr陣列所得到結果的正確性和演算法執行時間

templatevoid testsort(const string &sortname, void (*sort)(t, int), t arr, int n)

}#endif //inc_04_insertion_sort_selectionsort_h

插入函式(主函式)**

#include #include #include "sorttesthelper.h"

#include "selectionsort.h"

using namespace std;

/*//一,沒有優化的插入排序(交換法)

templatevoid insertionsort(t arr, int n)

return;}*/

//二,優化後的插入排序 (複製法)

//寫法三 :

templatevoid insertionsort(t arr, int n)

arr[j] = e;

}}// 比較selectionsort和insertionsort兩種排序演算法的效能效率

// 此時, 插入排序比選擇排序效能略低

int main() {

int n = 20000;

cout進行測試:

1.首先看一下沒有進行優化的[寫法一:]插入排序和選擇排序效能比較:

2.然後是沒有進行優化的[寫法二:]插入排序和選擇排序效能比較:

可見雖然效能都差不多,但是寫法二明顯比寫法一的**更漂亮

結論:在隨機的,無序的情況下,即是插入排序沒有優化但是它的效能依然比選擇排序好

3.優化後的插入排序與選擇排序比較:

可見此時插入排序的效能遠遠大於選擇排序

排序演算法詳解 選擇 插入 歸併和快排

特點 每次從待排序序列中選取最小值最為當前元素值 流程 已排好序的陣列為a 0,i 1 將未排序序列a i,n 中最小值賦給a i const int maxn 10000 int a maxn void selectsort int a,int n 特點 將未排序元素插入到已排序元素的合適位置上 ...

選擇排序 與 插入排序

中心思想 通過一次遍歷後,將最小的元素放到 前面 以此類推 在遍歷過程中記錄位置的是下標索引 選擇排序 include using namespace std template typename t void selectsort t arr,int n swap arr i arr mininde...

演算法 插入排序與選擇排序

一 插入排序 1 直接插入排序是一種簡單的插入排序法,其基本思想是 把待排序的記錄按其關鍵碼值的大小逐個插入到一 個已經排好序的有序序列中,直到所有的記錄插入完為止,得到乙個新的有序序列 思想十分簡單,演算法實現如下 直接插入排序 越有序插入越快 將每乙個數與前面所有排好序的數字相比較,如果大了 直...