减少判断的插入排序c++版
基于这个https://www.cnblogs.com/yang901112/p/11330900.html插入排序的改动
1 #include <iostream> 2 3 using namespace std; 4 5 template<class T> 6 void InsertionSort_2(T *q, int len); 7 8 int main() 9 { 10 int q[] = {0,8,5,7,4,0,9,6,2,3,1}; 11 InsertionSort_2(q, 10); 12 for(int i=1; i<=10; i++) 13 { 14 cout << q[i] << ' '; 15 } 16 return 0; 17 } 18 19 template<class T> 20 void InsertionSort_2(T *q, int len) 21 { 22 //注意:wait<=len 23 for(int wait=2; wait<=len; ++wait) 24 { 25 T tem = q[wait]; 26 q[0] = tem;//这里将q[0]作为循环条件 27 int line_up = wait-1; 28 while(q[0] < q[line_up])//这里只需要一个条件就可以了 29 { 30 q[line_up+1] = q[line_up]; 31 line_up--; 32 } 33 q[line_up+1] = q[0]; 34 } 35 }
这里将while 部分改动一下
1 #include <iostream> 2 3 using namespace std; 4 5 template<class T> 6 void InsertionSort_2(T *q, int len); 7 8 template<class T> 9 void Insert(const T& m, T *b, int n); 10 11 int main() 12 { 13 int q[] = {0,8,5,7,4,0,9,6,2,3,1}; 14 InsertionSort_2(q, 10); 15 for(int i=1; i<=10; i++) 16 { 17 cout << q[i] << ' '; 18 } 19 return 0; 20 } 21 22 template<class T> 23 void InsertionSort_2(T *q, int len) 24 { 25 for(int wait=2; wait<=len; ++wait) 26 { 27 T tem = q[wait]; 28 Insert(tem, q, wait-1); 29 // q[0] = tem; 30 // int line_up = wait-1; 31 // while(q[0] < q[line_up]) 32 // { 33 // q[line_up+1] = q[line_up]; 34 // line_up--; 35 // } 36 // q[line_up+1] = q[0]; 37 } 38 } 39 40 template<class T> 41 void Insert(const T& m, T *b, int n) 42 { 43 b[0] = m; 44 while(b[0] < b[n]) 45 { 46 b[n+1] = b[n]; 47 n--; 48 } 49 b[n+1] = b[0]; 50 51 }