插入排序

  //升序插入排序
      public static int[] insertSort(int[] a) {
          for(int i = 1; i < a.length; i++) {
              int j = i-1;
              int tmp = a[i];
             while(j >= 0 && a[j] > tmp) {
                  a[j+1] = a[j];
                  j = j -1;
              }
             a[j+1] = tmp;
         
        }
         
         return a;
     }
     
     //降序插入排序
     public static int[] insertSortDesc(int[] a) {
         for(int j=1; j < a.length; j++) {
             int i = j - 1;
             int key = a[j];
             while(i >= 0 && a[i] < key) {
                 a[i+1] = a[i];
                --i;
             }
             a[i+1] = key;
         }
         return a;
     }

 

你可能感兴趣的:(java,算法,插入排序)