JavaScript selection Sorting method

Source: Internet
Author: User

Select the sorting principle:

1. In the first traversal, find the smallest array element and then exchange it with the first array element.

2. In the second traversal, find the second small array element and swap it with the second array element.

3, and so on. If there are n elements, the sort is completed after a maximum of N-1 traversal.

Example:

The sample results show:

<!doctype html>
<meta charset= "Utf-8" >
<title> Select sorting Method </title>
<script>
var numbles = new Array (12,2,9,68,100,137,78,24,89,16);//Initialize one-dimensional array

/* Number of outputs before sorting */
document.write ("Number before sorting:")
for (Var i=0;i < numbles.length;i++) {
document.write (Numbles[i] + ",");
}
document.write ("<br/>");


var temp1 = 0; Used for each traversal is the smallest temporary variable stored at the time of comparison
var temp2 = 0; Temporary storage variables used for swapping at the end of a single traversal
var index = 0; Records the array index value that occurs when each iteration is minimized.

/* Select sorting algorithm: Ascending */
for (Var i=0;i < numbles.length-1;i++) {//up to traverse N-1 times
Temp1 = Numbles[i];
index = i;
for (var j = I;j < numbles.length-1;j++) {
if (Temp1 <= numbles[j+1]) {
}else{
Temp1 = numbles[j+1];
index = (j+1);
}
}

/* At the end of a traversal, swap the value of the starting position of the traverse and the minimum value of the Traverse to find a location */
Temp2 = Numbles[i];
Numbles[i] = Temp1;
Numbles[index] = Temp2;
}

/* Output sorted array elements */
document.write ("sorted number:");
for (Var i=0;i < numbles.length;i++) {
document.write (Numbles[i] + ",");
}
</script>

<body>
</body>

JavaScript selection Sorting method

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.