插入排序反序排序

package com.cn.gao;
//插入排序反序排序
public class InsertionSort {
    public static final int SIZE=10;
    //插入排序反序排序算法
    public static void insertionSort(int a[], int n){
        int i,j,temp;
        for(i=1;i<n;i++){
            temp=a[i];
            for(j=i-1;j>=0;j--){
                if(a[j]<temp){
                    a[j+1]=a[j];
                }else{
                    break;
                }
            }
            a[j+1]=temp;
            System.out.print("第"+i+"次排序的结果为:");
            for(j=0;j<n;j++){
                System.out.print(" "+a[j]);
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
           int[] a = new int[SIZE];
            //为数组赋值
            for(int i=0;i<a.length;i++){
                a[i] = (int) (100 + Math.random()*100);
            }
            //输出排序前的数组
            System.out.println("排序前的数组为:");
            for(int i=0;i<a.length;i++){
                System.out.print(a[i]+" ");
            }
            System.out.println();
            //对数组排序
            insertionSort(a,SIZE);
            //输出排序后的数组
            System.out.println("排序后的数组为:");
            for(int i=0;i<a.length;i++){
                System.out.print(a[i]+" ");
            }
            System.out.println();


    }

}

 

posted @ 2015-05-07 08:21  ~风轻云淡~  阅读(561)  评论(0编辑  收藏  举报