选择排序法之Java实现

       选择法排序的基本思想是首先从待排序的n个数中找出最小的一个与array[0]对换;再将array [1]到array [n]中的最小数与array [1]对换,依此类推。每比较一轮,找出待排序数中最小的一个数进行交换,共进行n-1次交换便可完成排序。选择法排序每执行一次外循环只进行一次数组元素的交换,可使交换的次数大大减少。

       下图演示这一过程:

 

          代码实现:

        

[java] view plain copy
 
  1. public class SelectSort{  
  2.     public static void main(String [] args){  
  3.       
  4.         int a[] = {1, 2, 3, 56, 45, 22, 22, 26, 89, 99, 100};  
  5.           
  6.         System.out.println("排序前:");  
  7.         for (int i = 0; i < a.length; ++ i){  
  8.             System.out.print(a[i] + " ");  
  9.         }  
  10.           
  11.         selectSort(a);  
  12.           
  13.         System.out.println("\n");  
  14.         System.out.println("排序后:");  
  15.         for (int i = 0; i < a.length; ++ i){  
  16.             System.out.print(a[i] + " ");  
  17.         }  
  18.     }  
  19.       
  20.     public static void selectSort(int a[]){  
  21.       
  22.         int min = 0;  
  23.         int temp = 0;  
  24.           
  25.           
  26.         for (int i = 0; i < a.length - 1; ++ i){  
  27.           
  28.             min = i;  
  29.             for (int j = i + 1; j < a.length; ++ j){  
  30.                 if (a[min] > a[j]){  
  31.                     min = j;  
  32.                 }  
  33.             }  
  34.               
  35.             if (min != i){  
  36.                 temp = a[min];  
  37.                 a[min] = a[i];  
  38.                 a[i] = temp;  
  39.             }  
  40.         }  
  41.     }  
  42. }  


         执行效果如图:

更多java学习视频:www.makeru.com.cn/?t=12

posted @ 2018-03-09 13:47  慧心的眼眸  阅读(157)  评论(0编辑  收藏  举报