selection sort

selection sort

analyze

  • Suppose an unordered array has been given, and now it needs to be sorted in a certain order. Now we use the selection sort method, which selects the largest element from the array each time and swaps it with the last element of the array, making the last element of the array the largest.

  • As the sorting progresses, the number of elements that need to be checked each time is gradually reduced, and only one element needs to be checked at the last time. In this case, why is the running time still O (*n*2)? Good question, it's related to constants in big-O notation. Chapter 4 will explain in detail, but only briefly mentioned here.

    You're right, you don't need to check n elements every time . The first time n elements need to be checked, but then the number of elements checked is n - 1, n - 2, …, 2, and 1. The average number of elements per check is 1/2 × n , so the running time is O ( n × 1/2 × n ). But big-O notation omits constants such as 1/2 (see Chapter 4 for a full discussion of this), so it is simply written O ( n × n ) or O (*n*2).

    ​ — "Algorithm Diagram"

Code

C language implementation

Because the deletion of arrays in C is more troublesome, I did not choose the smallest element each time according to the idea in "Algorithm Diagram", but chose the largest one.

void SelectionSort(int arr[], int length){  
    //C在函数中传数组长度较为麻烦,所以在数组定义出就将长度定义好传了过来

    int i, temp,biggest_index = 0;
    while (length){
         biggest_index = 0;
        for (i = 0; i < length; i++){
            if (arr[biggest_index] < arr[i]){
                biggest_index = i;
            }
        }
        printf("%d\n", arr[biggest_index]);
        temp = arr[biggest_index];
        arr[biggest_index] = arr[length - 1];
        arr[length -1] = temp;
        length --;
    }

}

JAVA language implementation

JAVA realizes the idea with C.

public int[] SelectionSort(int[] arr) {
        int length = arr.length;
        int biggestIndex;
        int i, temp;

        while(length > 0) {
            biggestIndex = 0;
            for(i = 0; i < length; i ++) {
                if(arr[biggestIndex] < arr[i]) {
                    biggestIndex = i;
                }
            }
            temp = arr[biggestIndex];
            arr[biggestIndex] = arr[length - 1];
            arr[length - 1] = temp;
            System.out.println(arr[length - 1]);
            length --;
        }
        return arr;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325689762&siteId=291194637