基本排序算法——选择排序java实现

选择排序与冒泡排序有很大的相同点,都是一次遍历结束后能确定一个元素的最终位置,其主要思路是,一次遍历选取最小的元素与第一个元素交换,从而使得一个个元素有序,而后选择第二小的元素与第二个元素交换,知道,最后只剩下一个元素,起就是最大的元素,此时排序完成。

代码如下;eclipse 4.3 jdk1.6

 1 package basic.sort;
 2 
 3 import java.util.Arrays;
 4 import java.util.Random;
 5 
 6 public class SelectSort {
 7     
 8     
 9     public static <AnyType extends Comparable<? super AnyType>>
10     void selectSortOnce(AnyType a[]){
11         int minIndex = 0;
12         AnyType temp;
13         if((a==null)||(a.length==0)){
14             return ;
15         }
16         for(int i=0; i<a.length; i++){
17             minIndex = i;                        //无序区的最小数据数组下标
18             for(int j=i+1; j<a.length; j++){    //在无序区中找到最小数据并保存其数组下标
19                 if(a[j].compareTo(a[minIndex]) < 0){            
20                     minIndex = j;
21                 }
22             }
23             if(minIndex!=i){                    //如果不是无序区的最小值位置不是默认的第一个数据,则交换之。
24                 temp = a[i];
25                 a[i] = a[minIndex];
26                 a[minIndex] = temp;
27             }
28         }
29     }
30     
31     public static void main(String[] args){
32         Random rand = new Random();
33         Integer[] arr = new Integer[10];
34         for(int i = 0 ;i <10 ;i++){
35             arr[i] = rand.nextInt(1000);
36         }
37         println(Arrays.toString(arr));
38         selectSortOnce(arr);
39         println(Arrays.toString(arr));
40     }
41     
42     public static void println(String str){
43         System.out.println(str);        
44     }
45 }

j继续努力

原文地址:https://www.cnblogs.com/xuddong/p/3290359.html