集册 Java实例教程 使用插入排序对数组排序。

使用插入排序对数组排序。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

380
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用插入排序对数组排序。
/* 来 自 时 代      J a v a   公   众 号 - nowjava.com*/

import java.security.SecureRandom;

import java.util.Arrays;


public class Main

{

   // sort array using insertion sort

   public static void insertionSort(int[] data)                

   {

      // loop over data.length - 1 elements           

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

      {

         int insert = data[next]; // value to insert

         int moveItem = next; // location to place element
         /**
         nowjava.com
         **/


         // search for place to put current element             

         while (moveItem > 0 && data[moveItem - 1] > insert)

         {

            // shift element right one slot         

            data[moveItem] = data[moveItem - 1];

            moveItem--;                             

         } 


         data[moveItem] = insert; // place inserted element    

         printPass(data, next, moveItem); // output pass of algorithm

      }                                             

   }


   // print a pass of the algorithm

   public static void printPass(int[] data, int pass, int index)

   {

      System.out.printf("after pass %2d: ", pass);


      // output elements till swapped item

      for (int i = 0; i < index; i++)

         System.out.printf("%d  ", data[i]);


      System.out.printf("%d* ", data[index]); // indicate swap


      // finish outputting array

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

         System.out.printf("%d  ", data[i]);


      System.out.printf("%n               "); // for alignment


      // indicate amount of array that?s sorted

      for(int i = 0; i <= pass; i++)

         System.out.print("--  ");

      System.out.println();

   } 


   public static void main(String[] args)

   {

      SecureRandom generator = new SecureRandom();


      int[] data = new int[10]; // create array


    
展开阅读全文