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