写一个直接插入法排序函数利用该函数对数组a按从小到大的次序并显示最终结果
时间: 2023-12-15 14:05:36 浏览: 28
以下是直接插入法排序函数的实现:
```c++
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
```
该函数的参数是一个整数数组和该数组的长度,它使用直接插入法对数组进行从小到大的排序。
接下来是利用该函数对数组a进行排序并显示最终结果的代码:
```c++
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n);
int main() {
int a[] = { 5, 2, 8, 3, 1 };
int n = sizeof(a) / sizeof(a[0]);
insertionSort(a, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
Sorted array: 1 2 3 5 8
```
数组a已经按从小到大的次序排序完成了。