每次(例如第 i 次, i = 0,1,...,n-2) 从后面 n-i 个待排的数据元素中选出关键字最小的元素,做为有序元素序列 i 个元素。
分解:
动图:
文件:Sort.hios
#ifndef SORT_H #define SORT_H #include "Object.h" namespace DTLib { class Sort : public Object { public: template <typename T> static void Select(T array[], int len, bool min2max = true) { for (int i=0; i<len; ++i) { int min = i; for (int j=i+1; j<len; ++j) { if ((min2max ? (array[min] > array[j]) : (array[min] < array[j]))) { min = j; } } if (min != i) { Swap(array[i], array[min]); } } } private: Sort(); Sort(const Sort&); Sort &operator= (const Sort&); template <typename T> static void Swap(T &a, T &b) { T c(a); a = b; b = c; } }; } #endif // SORT_H
文件:main.cpp编程
#include <iostream> #include "Sort.h" using namespace std; using namespace DTLib; int main() { int a[5] = {3, 4, 1, 0, 2}; Sort::Select(a, 5); for (int i=0; i<5; ++i) { cout << a[i] << " "; } cout << endl; Sort::Select(a, 5, false); for (int i=0; i<5; ++i) { cout << a[i] << " "; } return 0; }
输出:spa
0 1 2 3 4 4 3 2 1 0
当插入第 i (i>=1) 个数据元素时,前面的 V[0], V[1],...,v[i-1] 已经排好;这时,用V[i]的关键字与V[0], V[1],...,v[i-1]的关键字进行比较,找到位置后将V[i]插入,原来位置上的对象向后顺移。
分解:
动图
文件:Sort.hcode
#ifndef SORT_H #define SORT_H #include "Object.h" namespace DTLib { class Sort : public Object { public: template <typename T> static void Select(T array[], int len, bool min2max = true) // O(n*n) { for (int i=0; i<len; ++i) { int min = i; for (int j=i+1; j<len; ++j) { if ((min2max ? (array[min] > array[j]) : (array[min] < array[j]))) { min = j; } } if (min != i) { Swap(array[i], array[min]); } } } template <typename T> static void Insert(T array[], int len, bool min2max = true) // O(n*n) { for (int i=1; i<len; ++i) { T e = array[i]; int k = i; for (int j=i-1; (j>=0) && (min2max ? (e < array[j]) : (e > array[j])); --j) { array[j+1] = array[j]; k = j; } if (i != k) { array[k] = e; } } } private: Sort(); Sort(const Sort&); Sort &operator= (const Sort&); template <typename T> static void Swap(T &a, T &b) { T c(a); a = b; b = c; } }; } #endif // SORT_H
文件:main.cpp对象
#include <iostream> #include "Sort.h" using namespace std; using namespace DTLib; int main() { int a[5] = {3, 4, 1, 0, 2}; Sort::Insert(a, 5); for (int i=0; i<5; ++i) { cout << a[i] << " "; } cout << endl; Sort::Insert(a, 5, false); for (int i=0; i<5; ++i) { cout << a[i] << " "; } return 0; }
输出:blog
0 1 2 3 4 4 3 2 1 0
- 选择排序每次选择未排元素中的最小元素
- 插入排序每次将第 i 个元素插入前面 i -1 个已排元素中
- 选择排序是不稳定的排序法,插入排序是稳定的排序方法
- 选择排序和插入排序的时间复杂度为 O(n*n)
以上内容整理于狄泰软件学院系列课程,请你们保护原创!排序