#include <iostream>
using namespace std;
int n = 5 , m;
int a[5] = {6 , 1 , 9 , 5 , 1};
int main()
{
for ( int i = 1 ; i < n ; i++ )
{
int now = a[i] , j;
for ( j = i - 1 ; j >= 0 && a[j] > now ; j-- ){
a[j + 1] = a[j];
a[j] = now;
}
}
for ( int k = 0 ; k < n ; k++ )
printf("%d " , a[k]);
//cout << a[k] << " ";
return 0;
}
第二种
#include <iostream>
using namespace std;
int n = 5 , m;
int a[5] = {6 , 1 , 9 , 5 , 1};
int main()
{
for ( int i = 1 ; i < n ; i++ )
{
int now = a[i] , j;
for ( j = i - 1 ; j >= 0 ; j-- )
if ( a[j] > now )
a[j + 1] = a[j];
else break;
//此处+1是因为退出循环时J--了,+1是为了回到最后一个交换的元素
//j必须在内循环外定义,否则外循环看不见,这就是变量的作用域
a[j + 1] = now;
}
for ( int k = 0 ; k < n ; k++ )
printf("%d " , a[k]);
//cout << a[k] << " ";
return 0;
}
第三种(while循环实现)
#include <iostream>
using namespace std;
int n = 5 , m;
int a[5] = {6 , 1 , 9 , 5 , 1};
int main()
{
for ( int i = 1 ; i < n ; i++ )
{
int now = a[i] , j = i - 1;
while((j >= 0) && (now < a[j])){
a[j + 1] = a[j];
j--;
}
//此处+1是因为退出循环时J--了,+1是为了回到最后一个交换的元素
//j必须在内循环外定义,否则外循环看不见,这就是变量的作用域
a[j + 1] = now;
}
for ( int k = 0 ; k < n ; k++ )
printf("%d " , a[k]);
//cout << a[k] << " ";
return 0;
}