插入排序

/**
* 插入排序
* @author Administrator
*
*/
public class InsertSort {

void insertSort(int[] a){
int temp=0;
      for(int i=1;i<a.length; i++){
           if (a[i]<a[i-1]){
               temp = a[i];  //1
               a[i] = a[i-1]; //2
               int j=0;
               // 继续和前面的进行比较
               for( j=i-2; j>=0; j--){
                    if(temp < a[j]){
                    a[j+1] =a[j];//3
                    }
                    if(temp > a[j]){
                    a[j+1] =temp;//3
                    break;
                    }
               }
               if(j==-1){
               a[j+1] = temp;//4
               }
           
           }
      }
}


public static void insertionSort(int[] data) {

for (int index = 1; index < data.length; index++) {

int key = data[index];

int position = index;

// data[position - 1].compareTo(key) > 0表示升序。

//data[position - 1].compareTo(key) < 0表示降序

while (position > 0 && data[position - 1]> key) {

data[position] = data[position - 1];

position--;

}

data[position] = key;

}

}

public static void main(String[] args) {

InsertSort insertSort=new InsertSort();
int[] a={3,2,6,9,7,1,4,5};
insertSort.insertionSort(a);

for(int i:a){
System.out.println(i);
}

}

}

你可能感兴趣的:(插入排序)