python语言代码:
代码Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 def InsertSort(numbers,n):
for i in range(1,n):
j = i-1
tem = numbers[i]
while numbers[j]>tem and j>=0:
numbers[j+1] = numbers[j]
j -= 1
else:
numbers[j+1] = tem
print "Onthe sort:",numbers
a = [9,8,7,6,5,4,3,2,1,0]
print "BeforeSort:",a
InsertSort(a, 10)
print "After Sort:",a
最后输出为:
BeforeSort: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Onthe sort: [8, 9, 7, 6, 5, 4, 3, 2, 1, 0]
Onthe sort: [7, 8, 9, 6, 5, 4, 3, 2, 1, 0]
Onthe sort: [6, 7, 8, 9, 5, 4, 3, 2, 1, 0]
Onthe sort: [5, 6, 7, 8, 9, 4, 3, 2, 1, 0]
Onthe sort: [4, 5, 6, 7, 8, 9, 3, 2, 1, 0]
Onthe sort: [3, 4, 5, 6, 7, 8, 9, 2, 1, 0]
Onthe sort: [2, 3, 4, 5, 6, 7, 8, 9, 1, 0]
Onthe sort: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
Onthe sort: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After Sort: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
C语言实现代码:
代码Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->#include<stdio.h>
void insertSort(int a[10],int n)
{
int i,j,k;
for(i=1;i<n;i++)
{
int tem = a[i];
j = i - 1;
while(a[j]>tem && j>=0)
{
a[j+1] = a[j];
j--;
}
a[j+1] = tem;
for(k=0;k<10;k++)
{
printf("%d",a[k]);
}
printf("\n");
}
}
int main()
{
int b[10] = {9,8,7,6,5,4,3,2,1,0};
int i;
for(i=0;i<10;i++)
{
printf("%d",b[i]);
}
printf("\n");
insertSort(b,10);
for(i=0;i<10;i++)
{
printf("%d",b[i]);
}
}
最后输出:
9876543210
8976543210
7896543210
6789543210
5678943210
4567893210
3456789210
2345678910
1234567890
0123456789
时间: 2024-10-24 02:04:53