java插入排序算法

代码
1 public class CharuSort {
2 public static void main(String[] args){
3 int[] sort={4,6,3,9,5};
4 Sort(sort);
5 for(int i=0;i<sort.length;i++)
6 System.out.print(sort[i]+" ");
7 }
8
9 public static void Sort(int[] sort){
10 int i; //为扫描次数
11   int j; //定为比较得元素
12 for(i=1;i<sort.length;i++){ //扫描次数为sort.length-1
13 int temp; //temp用来暂存数据
14 temp=sort[i];
15 j=i-1;
16 while(j>=0&&temp<sort[j]){ //如果第二个元素小于第一个元素
17 sort[j+1]=sort[j]; //把所有的元素往后推一个位置
18 j--;
19 }
20 sort[j+1]=temp; //最小的元素放到第一个位置
21 }
22 }
23 }

 

posted @ 2010-05-29 10:57  莫萧  阅读(636)  评论(2编辑  收藏  举报