Sorting data (putting data in a particular order, such as ascending or descending) is one of the most important computing functions. A bank sorts all checks by account number so that it can prepare individual bank statements at the end of each month. Telephone com-panies sort their lists of accounts by last name and, within that, by first name, to make it easy to find phone numbers. Virtually every organization must sort some data—in many cases, massive amounts of data. Sorting data is an intriguing problem that has attracted some of the most intense research efforts in the field of computer science.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<!-- Fig. 10.9: Sort.html -->
<!-- Sorting an array with sort. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<title>Sorting an Array with Array Method sort</title>
var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];
document.writeln( "<h1>Sorting an Array</h1>" );
outputArray( "Data items in original order: ", a );
a.sort( compareIntegers ); // sort the array
outputArray( "Data items in ascending order: ", a );
// output the heading followed by the contents of theArray
function outputArray( heading, theArray )
document.writeln( "<p>" + heading +
theArray.join( " " ) + "</p>" );
} // end function outputArray
// comparison function for use with sort
function compareIntegers( value1, value2 )
return parseInt( value1 ) - parseInt( value2 );
} // end function compareIntegers
Fig. 10.9 | Sorting an array with sort.
Method sort takes as its optional argument the name of a function (called the com-parator function) that compares its two arguments and returns one of the following:
a negative value if the first argument is less than the second argument
zero if the arguments are equal, or
a positive value if the first argument is greater than the second argument
This example uses function compareIntegers (defined in lines 27–30) as the comparator function for method sort. It calculates the difference between the integer values of its two arguments (function parseInt ensures that the arguments are handled properly as inte-gers). If the first argument is less than the second argument, the difference will be a nega-tive value. If the arguments are equal, the difference will be zero. If the first argument is greater than the second argument, the difference will be a positive value.
Line 16 invokes Array object a’s sort method and passes function compareIntegers as an argument. Method sort receives function compareIntegers as an argument, then uses the function to compare elements of the Array a to determine their sorting order.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.