集册 Java实例教程 使用选择排序对数组排序。

使用选择排序对数组排序。

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

378
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用选择排序对数组排序。

import java.security.SecureRandom;

import java.util.Arrays;


public class Main/*NowJava.com - 时代Java 提 供*/

{

   // sort array using selection sort

   public static void selectionSort(int[] data)              

   {

      // loop over data.length - 1 elements      

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

      {

         int smallest = i; // first index of remaining array
//来自 时 代 J a v a - nowjava.com

         // loop to find index of smallest element              

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

            if (data[index] < data[smallest])             

               smallest = index;                                


         swap(data, i, smallest); // swap smallest element into position

         printPass(data, i + 1, smallest); // output pass of algorithm  

      }                                          

   } 


   // helper method to swap values in two elements

   private static void swap(int[] data, int first, int second)

   {

      int temporary = data[first]; // store first in temporary

      data[first] = data[second]; // replace first with second

      data[second] = temporary; // put temporary in second

   } 


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

   {

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


      // output elements till selected 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 j = 0; j < pass; j++)

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

      System.out.println(); 

   } 


   public static void main(String[] args)

   {

      SecureRandom generator = new SecureRandom();


      int[] data = new int[
展开阅读全文