Brief Introduction :
Using JavaScript to sort a set of numbers, JS has no direct numeric comparison function that can be invoked, so write yourself a quick sort of
Knowledge Points:
1. Regular expression extracts a string of positive and negative numbers
2. Str turn number back to list
3. JS object sort class declaration and definition
4. Sort class constructor, member function definition method (prototype)
5. Fast sorting algorithm
Code :
Copy Code code as follows:
<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html"; Charset=utf-8 "/>
<html>
<title>quick sort</title>
<head>
<script type = "Text/javascript" >
/*************get number from input***********/
function Getnumlist () {
var result = "";
var nums = document.getElementById (' numbers '). Value;
var reg =/([-][1-9][0-9]*) | ([1-9][0-9]*)/g;
var numstrlist = Nums.match (reg);
var numlist = new Array ();
if (numstrlist!= null) {
for (var i = 0;i < numstrlist.length;i++) {
var intnumber = parseint (numstrlist[i));
Numlist.push (intnumber);
}
}
return Mainprogram (numlist);
};
/*****************main*************************/
function Mainprogram (numlist) {
var sort = new Sort (numlist);
var sortedlist = Sort.getsortedlist ();
if (SortedList = null)
document.getElementById (' result '). InnerHTML = "wrong INPUT";
else{
document.getElementById (' result '). InnerHTML = Sortedlist.join (', ');
}
}
/**************sort class***********************/
var Sort = function (list) {
this.resultlist = list;
};
Sort.prototype.Partition = function (start,end) {
var basevalue = This.resultlist[start];
var basepos = start;
for (var j = start + 1;j <= end;j++) {
if (Basevalue > This.resultlist[j]) {
basepos++; Move the base position
this. Swap (BASEPOS,J);
}
}
//Move the base value to the correct place, before are smaller, behind are bigger
this. Swap (Start,basepos);
return basepos;
}
Sort.prototype.QuickSort = function (start,end) {
if (Start < end) {
var basepos = this. Partition (Start,end);
this. QuickSort (START,BASEPOS-1);
this. QuickSort (Basepos + 1, end);
}
};
Sort.prototype.Swap = function (pos1,pos2) {
var temp = this.resultlist[pos1];
THIS.RESULTLIST[POS1] = This.resultlist[pos2];
This.resultlist[pos2] = temp;
}
Sort.prototype.getSortedList = function () {
this. QuickSort (0,this.resultlist.length-1);
return this.resultlist;
};
</script>
</head>
<body>
<B> Quick sort</b>
<br>
<br>
<input type= "text" id = ' numbers ' value = '/>
<input type = ' button ' value = ' exec ' onclick = ' getnumlist () '/>
<br>
<br>
<b>sorted LIST: <B> <b id = ' Result ' ></b>
</body>
</html>
Output: