選擇排序的實現以及效能測試

2021-09-01 03:04:46 字數 1157 閱讀 8350

用c++語言實現

選擇排序(selection sort)是一種簡單直觀的排序演算法。它的工作原理是每一次從待排序的資料元素中選出最小(或最大)的乙個元素,存放在序列的起始位置,直到全部待排序的資料元素排完。 選擇排序是不穩定的排序方法(比如序列[5, 5, 3]第一次就將第乙個[5]與[3]交換,導致第乙個5挪動到第二個5後面)。

首先我們寫乙個用來測試的**

#ifndef inc_03_selection_sort_detect_performance_sorttesthelper_h

#define inc_03_selection_sort_detect_performance_sorttesthelper_h

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

namespace sorttesthelper

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

templatevoid printarray(t arr, int n)

// 判斷arr陣列是否有序

templatebool issorted(t arr, int n)

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

};#endif //inc_03_selection_sort_detect_performance_sorttesthelper_h

然後在主函式中實現選擇排序並進行測試:

#include #include "sorttesthelper.h"

using namespace std;

templatevoid selectionsort(t arr, int n)

}int main()

結果分析:

可見我們對20000個從1-----20000的隨機元素進行選擇排序最終用時0.69秒

完整的氣泡排序實現以及原理

氣泡排序 比較次數的公式 n n 1 2 原理 相鄰元素兩兩比較,值較大者往後放,第一次比較完畢,最大值出現在了最大索引處。public class bubblesort system.out.println 氣泡排序前 for int i num 第一次比較 是為了防止陣列越界 num.lengt...

java氣泡排序的實現以及優化

氣泡排序原理 1 比較相鄰的兩個元素,如果前者大於後者則交換位置 2 這樣對陣列第0個資料到n 1個資料進行遍歷比較一次後,最大的資料會移動到最後一位。3 n n 1,如果n 0則排序完成 實現 package zks public class bubblesort package zks publ...

堆的基本實現以及堆排序

heap.h pragma once include include include include include includetypedef int hpdatatype typedef struct heap heap void heapcreat heap hp,hpdatatype a,...