C语言代码
#include "stdio.h"
void array_printf(int a[],int n);
void sort_insert(int a[],int n);
int main()
{
int i,a[5] = {5,4,3,2,10};
sort_insert(a,5);
return 0;
}
void array_printf(int a[],int n){
int i ;
for (i = 0; i < n; ++i)
{
printf("%d ",a[i]);
}
printf("\n");
}
void sort_insert(int a[],int n){
int t,i,j,k;
// range of a : 0 -> n-1
for(i =1; i< n ; i++){
t = a[i]; //get a[i] into a temporary var
// compare a[i] with a[0 ~ i-1] , and insert a[i] into right position
for(j = 0; j< i; j++){
// compare a[j] vs t
// c1 a[j] <= t , continue
// c2 a[j] > t, insert t
//c2.1 move a[j~i-1] to a[j+1~i]
//c2.2 move t to a[j]
//c2.3 break the loop
//====> I forgot this step first.very bad answer!!!
if(a[j] > t) {
//c2.1
for(k=i ; k>j ; k--)
a[k] = a[k-1];
//c2.2
a[k] = t;
//c2.3
break;
}
}
array_printf(a,n);
}
}
JAVA
1 接口
import java.util.*;
interface Sort{
public void sort(List<Integer> source);
}
2 实现
import java.util.*;
class SortInsert implements Sort {
public void sort(List<Integer> a){
for(int i = 1 ; i < a.size() ; i++){
Integer t = a.get(i);
for(int j = 0 ; j < i ; j++){
if( a.get(j) > t){
for(int k = i ; k > j ; k--){
a.set(k,a.get(k-1));
}
a.set(j,t);
break;
}
}
}
}
}
3 测试
import java.util.*;
public class TestSort{
public static void main(String []args){
Sort s = new SortInsert();
List<Integer> list = new ArrayList<Integer>(Arrays.asList(4,20,1,3,2));
s.sort(list);
for(int i = 0;i<list.size();i++)
System.out.print(list.get(i)+" ");
}
}