java实现选择排序(selection_sort)

选择排序的概念就是从未排序中选择最小的元素放入到已排序元素的最后面。

下面是对一组整数进行排序。

 1 public class selectionSort {
 2     public static void main(String[] args){
 3         int[] toBeSorted = {1,54,3,8,6,0};
 4         
 5         
 6         for(int i = 0; i < toBeSorted.length; i++){
 7             for(int j = i+1; j < toBeSorted.length; j++){
 8                 if(toBeSorted[i] > toBeSorted[j]){
 9                     int temp = toBeSorted[i];
10                     toBeSorted[i] = toBeSorted[j];
11                     toBeSorted[j] = temp;
12                 }
13             }
14         }
15        
16         for(int i = 0; i <toBeSorted.length; i++){
17             System.out.print(toBeSorted[i]+" ");
18         }
19         
20     }
21 
22 }

 但是这种方法的效率不高。

原因如下:如果你要排序的数字是:2,4,6,7,3,5,1,9,8

当i=1的时候,4要与后面的3进行交换,然后与1再进行交换,这样进行两次交换就降低了效率。如果加上两个变量便会去除不必要的交换。代码如下:

public class selectionSort {
    public static void main(String[] args){
        int[] toBeSorted = {1,54,3,8,6,0};
        
        //k记录当前已排完序的最后一个元素的位置,
        //temp用于交换时候的临时变量
        //为了避免每次都要重新申请内存,所以将两个变量提出来放在函数外面
        int k, temp;
        for(int i = 0; i < toBeSorted.length; i++){
            k = i;
            for(int j = k+1; j < toBeSorted.length; j++){
                if(toBeSorted[k] > toBeSorted[j]){
                    k = j;
                }
            }
            if(k != i){
                temp = toBeSorted[i];
                toBeSorted[i] = toBeSorted[k];
                toBeSorted[k] = temp;
                
            }
        }
        
        for(int i = 0; i <toBeSorted.length; i++){
            System.out.print(toBeSorted[i]+" ");
        }
        
    }

}

最后来分析一下算法的复杂度:O(n*n)的。这是因为算法要进行循环排序。

这就意味值在n比较小的情况下,算法可以保证一定的速度,当n足够大时,算法的效率会降低。并且随着n的增大,算法的时间增长很快。因此使用时需要特别注意。

原文地址:https://www.cnblogs.com/fyymonica/p/2825515.html