直接排序算法 最简单的排序算法 可以自行查看一下原理再来看一下代码实现
#include<iostream>
using namespace std;
void displayarray1(int a[], int n);
int main() {
int a[] = { 67,48,23,81,38,19,52,40 };
int n = sizeof(a) / sizeof(a[0]);
cout << "排序前" << endl;
displayarray1(a, n);
//排序
int j;
int temp;
for ( int i = 1; i <n; i++)
{
temp = a[i];
for (j = i-1; i >=0&&temp<a[j];j--)
{
a[j + 1] = a[j];
}
a[j + 1] = temp;
cout << "第" << i << "趟排序结果" << endl;
displayarray1(a, n);
}
cout << "排序后" << endl;
displayarray1(a, n);
system("pause");
return 0;
}
void displayarray1(int a[], int n) {
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
运行结果: