-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample2.cpp
More file actions
64 lines (55 loc) · 1.23 KB
/
Copy pathexample2.cpp
File metadata and controls
64 lines (55 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Created by zing on 6/8/2020.
//
#include <iostream>
using namespace std;
//交换的函数模板
template<typename T>
void mySwap(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}
template<class T>
// 也可以替换成typename
//利用选择排序,进行对数组从大到小的排序
void mySort(T arr[], int len) {
for (int i = 0; i < len; i++) {
int max = i; //最大数的下标
for (int j = i + 1; j < len; j++) {
if (arr[max] < arr[j]) {
max = j;
}
}
if (max != i) //如果最大数的下标不是i,交换两者
{
mySwap(arr[max], arr[i]);
}
}
}
template<typename T>
void printArray(T arr[], int len) {
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void test01() {
//测试char数组
char charArr[] = "bdcfeagh";
int num = sizeof(charArr) / sizeof(char);
mySort(charArr, num);
printArray(charArr, num);
}
void test02() {
//测试int数组
int intArr[] = {7, 5, 8, 1, 3, 9, 2, 4, 6};
int num = sizeof(intArr) / sizeof(int);
mySort(intArr, num);
printArray(intArr, num);
}
int main() {
test01();
test02();
return 0;
}