Write a sort function that implements the sorting of numbers. The sorting method is implemented by the client function, the number of function parameters is two, the relationship of two parameters is the relationship between the sorted elements.

Source: Internet
Author: User
Tags throw exception

<script>
function Sortnumber (OBJ,FUNC)//define General sort function
{
Parameter validation, throws an exception if the first parameter is not an array or the second argument is not a function
if (! ( obj instanceof Array) | | ! (func instanceof Function))
{
var e = new Error (); Generate error message
E.number = 100000; Define the error number
E.message = "Invalid parameter"; Error description
Throw e; Throw exception
}
for (n in obj)//start sort
{
for (m in obj)
{
if (func (Obj[n],obj[m]))//Sort using callback function, the rule is set by the user
{
var tmp = Obj[n]; Create a temporary variable
Obj[n] = obj[m]; Exchanging data
OBJ[M] = tmp;
}
}
}
return obj; Returns the sorted array
}
function Greatthan (ARG1,ARG2)//callback function, user-defined collation
{
return Arg1 < arg2;
}
Try
{
var numary = new Array (5,8,6,32,1,45,6,89,9); Generate an array
document.write ("<li> before sorting:" +numary); Array before the output is sorted
Sortnumber (Numary,greatthan); Call sort function
document.write ("<li> after sorting:" +numary); Output sorted Array
}
catch (E)
{
Alert (e.number+ ":" +e.message);
}
</script>

The

writes a sort function to sort the numbers. The sorting method is implemented by the client function, the number of function parameters is two, the relationship of two parameters is the relationship between the sorted elements.

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.