#include <iostream>
using namespace std;
void swap(int* a, int* b);
void sort(int* arr, int n)//从小到大排序
{
for (int i = 1; i < n; i++)
{
int j = i - 1;
while (j >= 0 && arr[j] > arr[j + 1])
{
swap(&arr[j], &arr[j + 1]);
j--;
}
}
}
void swap(int* a, int* b)
{
int temp = 0;
temp = *b;
*b = *a;
*a = temp;
}
int main()
{
int n;
cout << "请输入数组的大小" << endl;
cin >> n;
int arr[500];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "接下来进行插入排序" << endl;
sort(arr, n);
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
插排对于冒泡排序法就是在一般情况下,算法复杂度小于O(n^2)
代码还是非常好理解的,写下练练手