47 选择排序和插入排序
原文:https://www.cnblogs.com/wanmeishenghuo/p/9683786.html 参考狄泰软件相关教程
添加选择排序:
#ifndef SORT_H #define SORT_H #include "Object.h" namespace DTLib { class Sort : public Object { 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; } public: template < typename T > static void Select(T array[], int len) { for(int i = 0; i < len; i++) { int min = i; for(int j = i + 1; j < len; j++) { if( array[min] > array[j] ) { min = j; } } if( min != i) { Swap(array[i], array[min]); } } } }; } #endif // SORT_H
测试程序如下:
#include <iostream> #include <cstring> #include "DTString.h" #include "LinkList.h" #include "Object.h" #include "Sort.h" using namespace std; using namespace DTLib; int main() { int array[] = {3, 1, 2, 5, 4}; Sort::Select(array, 5); for(int i=0; i < 5; i++) { cout << array[i] << endl; } return 0; }
结果如下:
给Select添加一个参数,支持从小到大排序和从大到小排序:
#ifndef SORT_H #define SORT_H #include "Object.h" namespace DTLib { class Sort : public Object { 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; } 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]); } } } }; } #endif // SORT_H
注意:选择排序是不稳定的。
添加插入排序操作:
#ifndef SORT_H #define SORT_H #include "Object.h" namespace DTLib { class Sort : public Object { 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; } 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]); } } } template < typename T > static void Insert(T array[], int len, bool min2max=true) { for(int i=1; i < len; i++) //从1开始,第0个元素没有必要插入操作 { int k = i; T e = array[i]; for(int j=i-1; (j>=0) && (min2max ? (array[j] > e) : (array[j] < e)); j--) { array[j+1] = array[j]; k = j; } if( k != i ) //赋值比“比较操作耗时” { array[k] = e; } } } }; } #endif // SORT_H
注意:插入排序是稳定的排序
选择排序的时间复杂度是O(n*n)
插入排序的时间复杂度是O(n*n)
小结:
posted on 2020-09-01 20:19 lh03061238 阅读(131) 评论(0) 编辑 收藏 举报