11. 检查数组是否有序函数

题目:

编写一个模板函数 is_sorted,当且仅当a[0 : n - 1]有序时,返回值为 true。测试你的代码。

思路:

数组可以升序有序,也可以降序有序,也可以所有元素均相等。我假设,当数组元素只有一个,或者数组所有元素均相等的时候,数组自然有序。

数组升序降序是未知的,尤其是开头有元素相等的情况下。于是我们换个角度考虑:升序,降序二者只能有其一,如果既有升序又有降序,那么自然判定为无序。

代码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template <typename T>
 5 bool is_sorted(const T* a, int size) {
 6     //only one item, ordered
 7     if (1 == size) {
 8         return true;
 9     }
10 
11     bool asc_ordered = false, desc_order = false;
12     for (int i = 0; i < size - 1; ++i) {
13         if (a[i] == a[i + 1]) {
14             continue;
15         } else if (a[i] < a[i + 1]) {
16             asc_ordered = true;
17         } else {
18             desc_order = true;
19         }
20         if (asc_ordered && desc_order) {
21             return false;
22         }
23     }
24     return true;
25 }
26 
27 int main() {
28     int a[5] { 0, 1, 2, 3, 4 };//asc_ordered
29     int b[5] { 5 ,4, 3, 2, 1 };//desc_ordered
30     int c[5] { 0, 0, 8, 0, 0 };//unordered
31     int d[5] { 8, 8, 5, 4, 3 };//equal and desc_ordered
32     int e[5] { 0, 0, 1, 2, 3 };//equal and asc_ordered
33     int f[1] { 0 };//single number,ordered
34     int g[5] { 1, 1, 1, 1, 1 };//all number equal
35 
36     cout << "a(should asc_ordered) : " << is_sorted(a, 5) << endl;
37     cout << "b(should desc_ordered) : " << is_sorted(b, 5) << endl;
38     cout << "c(should unordered) : " << is_sorted(c, 5) << endl;
39     cout << "d(should equal and desc_ordered) : " << is_sorted(d, 5) << endl;
40     cout << "e(should equal and asc_ordered) : " << is_sorted(e, 5) << endl;
41     cout << "f(should single number and ordered) : " << is_sorted(f, 1) << endl;
42     cout << "g(should all number equal and ordered) : " << is_sorted(g, 5) << endl;
43 
44     return 0;
45 }

 

posted @ 2020-02-13 22:27  Hello_Nolan  阅读(698)  评论(0编辑  收藏  举报