插入排序

来源:互联网 发布:安藤忠雄中山邸数据 编辑:程序博客网 时间:2024/06/06 02:02

创建一个有序的数组,之后从从无序数组中进行一个个插入,变成有序数组。

代码实现:

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);}}

0 0
原创粉丝点击