Java implementation of selection sorting (diagram + details)

Selection sort is a basic simple sorting method.

principle

1. Traverse the array, assuming that the element at the first index is the smallest element, and mark the index with min. Then, it is compared with the elements at other indexes in turn. If the element at the current index is less than the element at the min index, the min value is modified to the current index. Finally, you can find the index of the minimum element
2. Exchange the position of the element at the min index and the element at the first index in the current array
3. Assuming that the size of the array is n, repeat steps 1 and 2 (n-1) times, you can Complete sorting
Insert picture description here

Code

public class Selection {
    
    

    //交换a数组中索引x和索引y处的元素
    private static void exch(Comparable[]a,int x,int y){
    
    
        Comparable temp=a[x];
        a[x]=a[y];
        a[y]=temp;
    }
    //判断a元素是否小于b元素
    private static boolean less(Comparable a,Comparable b){
    
    
        return a.compareTo(b)<0;
    }

    public static void sort(Comparable[]a){
    
    
        final int N=a.length;
        //外层循环次数为N-1次
        for (int i = 0; i <N-1; i++) {
    
    
            //min标记最小处元素的索引
            int min=i;
            for (int j =i+1; j <N; j++) {
    
    
                if(less(a[j],a[min]))min=j;
            }
            //交换当前第一个索引处的元素和min索引处的元素
            exch(a,i,min);
        }

    }
    public static void main(String[] args) {
    
    
        Integer[]a=new Integer[50];
        for (int i = 0; i < a.length; i++) {
    
    
            a[i]=(int)(Math.random()*50);
        }
        System.out.println("排序前");
        for (int i = 0; i < a.length; i++) {
    
    
            System.out.print(a[i]+" ");
        }
        System.out.println("排序后");
        sort(a);
        for (int i = 0; i < a.length; i++) {
    
    
            System.out.print(a[i]+" ");
        }
    }
}

Complexity analysis

  • Time complexity: the number of comparisons is (n-1)+(n-2)...+1, the number of exchanges is n-1; the total number is (n+2)(n-1)/2~(n 2 ), So the time complexity is O(n 2 )

Guess you like

Origin blog.csdn.net/ln82799/article/details/109339758