您的位置:首页 > 其它

插入排序

2015-07-30 16:24 246 查看
public class ArrayUtil {
/**
*
* @param array
*/
  public static void printArray(int [] array){
    System.out.print("{");
    for(int i = 0;i < array.length;i++){
      System.out.print(array[i]);
      if(i < array.length - 1){
        System.out.print(",");
      }
    }
    System.out.println("}");
  }
}

public class InsertSort {
  public static void insertSort(int[] array) {

    if (array == null || array.length < 2) {
      return;
    }

    for (int i = 0; i < array.length; i++) {
      int currentValue = array[i];
      int position = i;
      for (int j = i - 1; j >= 0; j--) {
        if (array[j] > currentValue) {
          array[j + 1] = array[j];
          position = position - 1;
        } else {
          break;
        }
      }
      array[position] = currentValue;
   }
}

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] a = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1 };

    ArrayUtil.printArray(a);
    insertSort(a);
    ArrayUtil.printArray(a);
  }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: