`
kobe学java
  • 浏览: 249130 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

简单选择排序(Select Sort),java版

    博客分类:
  • java
 
阅读更多

转载:

 

http://blog.chenlb.com/2008/12/select-sort-for-java.html

简单选择排序(Select Sort),java版。

发表于:2008年12月28日 | 分类:算法 | 标签: sort | views(661)

版权信息: 可以任意转载, 转载时请务必以超链接形式标明文章原文出处, 即下面的声明.

 

原文出处:http://blog.chenlb.com/2008/12/select-sort-for-java.html

常用的简单排序方法中,除插入排序、冒泡排序,还有简单选择排序(有时候也直接说成是选排序)。

简单选择排序原理:从无序区域里选择最小(或最大)的添加到有序区里。一开始所有的数据都是在无序区里,排好一个,无序区个数就少一个。
时间复杂度:平均O(n2),最坏情况O(n2)。

示例代码:

  1. package com.chenlb.sort;  
  2.   
  3. import java.util.Arrays;  
  4.   
  5. public class SelectSort {  
  6.   
  7.     public static int[] sort(int[] datas) {  
  8.         for(int i=0; i<datas.length-1; i++) {  
  9.             int minIndex = i;  
  10.             int min = datas[i];  
  11.             for(int j=i+1; j< datas.length; j++) {//在后面, 找最小的.  
  12.                 if(datas[j] < min) {  
  13.                     minIndex = j;  
  14.                     min = datas[j];  
  15.                 }  
  16.             }  
  17.             if(minIndex != i) {  
  18.                 SortUtil.swap(datas, i, minIndex);  
  19.             }  
  20.         }  
  21.         return datas;  
  22.     }  
  23.   
  24.     public static void main(String[] args) {  
  25.         int[] datas = {5,1,3,4,9,2,7,6,5};  
  26.         sort(datas);  
  27.         System.out.println(Arrays.toString(datas));  
  28.   
  29.         datas = SortUtil.randomDates(10);  
  30.         sort(datas);  
  31.         System.out.println(Arrays.toString(datas));  
  32.     }  
  33.   
  34. }  

运行结果:

  1. [1, 2, 3, 4, 5, 5, 6, 7, 9]  
  2. [67, 81, 122, 394, 452, 509, 533, 536, 608, 861]  

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics