插入排序
#include <iostream>
#include <ctime>
using namespace std;
void sort(int arr[],int k)
{
if(k == 0)
return;
//对前k-1个元素进行排序
sort(arr,k-1);
//把位置k的元素插入到前面的部分
int x = arr[k];
int index = k-1;
while(index >= 0 && arr[index] > x)
{
arr[index+1] = arr[index];
index--;
}
arr[index+1] = x;
}
int main()
{
srand(time(NULL));
int n;
cin>>n;
int arr[n];
cout<<"Before ordering of data for:"<<endl;
for(int i=0;i<n;i++)
{
arr[i] = rand()%50;
cout<<arr[i]<<" ";
}
sort(arr,n);
cout<<endl<<"Sorted data:"<<endl;
for(int i = 0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}