创建一个有序的数组,之后从从无序数组中进行一个个插入,变成有序数组。
代码实现:
public class InsertSort {
InsertSort(int a[]){
int length = a.length;
for(int j = 1; j <= length - 1; j++){ //进行循环
int i = j - 1;
int temp = a[j]; //要插入的数字
while(a[i] > temp){ //在已排好序的序列中寻找应放入的位置
a[i + 1] = a[i]; //把较大的数前移
i --; //继续比较下一个数
if(i < 0)
break;
}
a[i + 1] = temp;
}
}
public static void main(String args[]){
int a[] = {6,8,9,43,89,5,7,3,};
InsertSort s = new InsertSort(a);
for(int n:a)
System.out.println(n);
}
}