zoukankan      html  css  js  c++  java
  • 选择排序法之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(" ");  
    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

  • 相关阅读:
    mkimage command not found
    Linux添加快捷启动方式 (Ubuntu Debian CentOS)
    CentOS下通过locale来设置字符集
    CentOS 安装中文输入法
    Centos 安装KScope1.6.2
    centos 配置NFS服务器
    Linux shell判断文件和文件夹是否存在
    数据库中Schema和Database有什么区别
    配置Tomcat使用https协议
    HTML font: 12px/1.5 Arial; 是什么意思
  • 原文地址:https://www.cnblogs.com/huan-huan/p/8533486.html
Copyright © 2011-2022 走看看