插入排序



package com.xj.www.sort;
/**
 * 插入排序算法
 *
 * @author xiongjing
 *
 */
public class InsertSort {
      /**
       * 插入排序算法具體流程實(shí)現(xiàn)如下: 插入算法通過(guò)比較和插入來(lái)實(shí)現(xiàn)排序。 1.首先對(duì)數(shù)組的前兩個(gè)數(shù)據(jù)進(jìn)行從小到大的排序。
       * 2.接著將第3個(gè)數(shù)據(jù)與排號(hào)需的兩個(gè)數(shù)據(jù)比較,將第3個(gè)數(shù)據(jù)插入合適的位置。 3.然后,將第4個(gè)數(shù)據(jù)插入已排好序的前3個(gè)數(shù)據(jù)中。
       * 4.不斷重復(fù)上述過(guò)程,直到把最后一個(gè)數(shù)據(jù)插入合適的位置。
       */
      final static int SIZE = 10;
      // 插入排序算法實(shí)現(xiàn),從小到大
      public static void insert(int[] a) {
            int i, j, temp;
            for (i = 1; i < a.length; i++) {
                  temp = a[i];
                  j = i - 1;
                  // 循環(huán)查找合適的位置
                  while (j >= 0 && temp < a[j]) {
                        a[j + 1] = a[j];
                        j--;
                  }
                  a[j + 1] = temp;
            }
      }
      // 插入排序算法實(shí)現(xiàn),從大到小
      public static void insertSort(int[] a) {
            int i, j, temp;
            for (i = 1; i < a.length; i++) {
                  temp = a[i];
                  j = i - 1;
                  // 循環(huán)查找合適的位置
                  while (j >= 0 && temp > a[j]) {
                        a[j + 1] = a[j];
                        j--;
                  }
                  a[j + 1] = temp;
            }
      }
      // 程序主入口
      public static void main(String[] args) {
            int[] shuzu = new int[SIZE];
            int i;
            for (i = 0; i < SIZE; i++) {
                  shuzu[i] = (int) (100 + Math.random() * (100 + 1));
            }
            System.out.println("排序前的數(shù)組為:");
            for (i = 0; i < SIZE; i++) {
                  System.out.print(shuzu[i] + " ");
            }
            System.out.print("\n");
             insert(shuzu);
//          insertSort(shuzu);
            System.out.println("排序后的數(shù)組為:");
            for (i = 0; i < SIZE; i++) {
                  System.out.print(shuzu[i] + " ");
            }
            System.out.print("\n");
      }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容