Select Sort---Direct selection sorting algorithm (JavaScript version)

Source: Internet
Author: User

In the sequence of numbers to be sorted, select the minimum (or maximum) number to exchange with the number of the 1th position, and then in the remaining number, find the minimum (or maximum) number of the 2nd position to exchange, and so on, until the n-1 element (the penultimate number) and the nth element (the last number) are compared.

functionsort (elements) { for(i = 0; i < elements.length; i++){    //Place the current position as a critical position (minimum position)    varKey =i; //find the position of the smallest value in the remaining series as a key position     for(varj = i + 1; J < Elements.length; J + +){      if(Elements[j] <Elements[key]) {Key=J; }    }        //Replace the value of the current position with the minimum value when the position of the minimum value is not the current position    if(Key! =i) {      varSwap =Elements[i]; Elements[i]=Elements[key]; Elements[key]=swap; }  }}varelements = [10,9,8,7,6,5,4,3,2,1,0];console.log (' Before: ' +elements); sort (elements); Console.log (' After: ' + elements);

Efficiency:

Time complexity: Best: O (n^2), Worst: O (n^2), average: O (n^2).

Space complexity: O (1).

Stability: Unstable, column such as, sequence 4 7 4 2 8, the first pass after the selection 4 and 2 Exchange, then the original sequence of 2 4 of the relative sequence is destroyed, so the selection is not a stable sorting algorithm.

Select Sort---Direct selection sorting algorithm (JavaScript version)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.