码迷,mamicode.com
首页 > 编程语言 > 详细

选择排序

时间:2017-02-19 10:28:48      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:style   log   sort   blog   http   static   black   图解   选择   

选择排序

用一个索引的位置上的元素与其他索引位置上的元素比较,小的前面,大的在后面.

    0索引开始,依次和后面元素比较,小的往前放,第一次完毕,最小值出现在了最小索引处

图解:

技术分享

代码实现

  1. public class Demo1_Array {
  2.  
  3.    public static void main(String[] args) {
  4.       int[] arr = {24, 69, 80, 57, 13};
  5.       //selectSort(arr);
  6.       print(arr);
  7.    }
  8.  
  9.    public static void print(int[] arr) {
  10.       for (int i = 0; i < arr.length; i++) {
  11.          System.out.print(arr[i] + " ");
  12.       }
  13.    }
  14.  
  15.    public static void selectSort(int[] arr) {
  16.       for (int i = 0; i < arr.length - 1; i++) { //只需要比较arr.length-1次
  17.          for (int j = i + 1; j < arr.length; j++) {
  18.             if(arr[i] > arr[j]) {
  19.                swap(arr,i,j);
  20.             }
  21.          }
  22.       }
  23.    }
  24.  
  25.    private static void swap(int[] arr,int i,int j) {
  26.       int temp = arr[i];
  27.       arr[i] = arr[j];
  28.       arr[j] = temp;
  29.    }
  30. }

选择排序

标签:style   log   sort   blog   http   static   black   图解   选择   

原文地址:http://www.cnblogs.com/wk520hll/p/6414654.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!