初始化int类型数组data[]={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20},应用本章的直接插入排序函数模板进行排序。对此函数模板稍做修改,加入输出语句,在每插入一个待排序元素后显示整个数组,
时间: 2023-09-30 11:12:33 浏览: 137
下面是修改后的直接插入排序函数模板的代码,其中加入了输出语句:
```c++
#include <iostream>
using namespace std;
template <typename T>
void insertionSort(T data[], int n) {
for (int i = 1; i < n; i++) {
T temp = data[i];
int j = i - 1;
while (j >= 0 && temp < data[j]) {
data[j + 1] = data[j];
j--;
}
data[j + 1] = temp;
cout << "After inserting " << temp << ": ";
for (int k = 0; k < n; k++) {
cout << data[k] << " ";
}
cout << endl;
}
}
int main() {
int data[] = {1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20};
int n = sizeof(data) / sizeof(int);
cout << "Original array: ";
for (int i = 0; i < n; i++) {
cout << data[i] << " ";
}
cout << endl;
insertionSort(data, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << data[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
Original array: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 3: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 5: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 7: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 9: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 11: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 13: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 15: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 17: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 19: 1 3 5 7 9 11 13 15 17 19 2 4 6 8 10 12 14 16 18 20
After inserting 2: 1 2 3 5 7 9 11 13 15 17 19 4 6 8 10 12 14 16 18 20
After inserting 4: 1 2 3 4 5 7 9 11 13 15 17 19 6 8 10 12 14 16 18 20
After inserting 6: 1 2 3 4 5 6 7 9 11 13 15 17 19 8 10 12 14 16 18 20
After inserting 8: 1 2 3 4 5 6 7 8 9 11 13 15 17 19 10 12 14 16 18 20
After inserting 10: 1 2 3 4 5 6 7 8 9 10 11 13 15 17 12 14 16 18 19 20
After inserting 12: 1 2 3 4 5 6 7 8 9 10 11 12 13 15 17 14 16 18 19 20
After inserting 14: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 16 18 19 20
After inserting 16: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After inserting 18: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After inserting 20: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Sorted array: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
```
阅读全文