简述: 用到javascript的排序一组数字,js没有直接的数字比较的函数可以调用,所以自己写了一个快速排序 知识点: 1. 正则表达式提取正负数字的string 2. str 转数字 放回列表 3. js的对象Sort类的声明及定义 4. Sort类构造函数、成员函数定义方式(prototype) 5. 快速排序算法 代码: 复制代码 代码如下: . Quick Sort <BR>/*************Get Number From Input***********/ <BR>function getNumList(){ <BR>var result = ""; <BR>var nums = document.getElementById('numbers').value; <BR>var reg = /([-][1-9][0-9]*)|([1-9][0-9]*)/g; <BR>var numStrList = nums.match(reg); <BR>var numList = new Array(); <BR>if(numStrList != null){ <BR>for(var i = 0;i < numStrList.length;i++){ <BR>var intNumber = parseInt(numStrList[i]); <BR>numList.push(intNumber); <BR>} <BR>} <BR>return MainProgram(numList); <BR>}; <br><br>/*****************Main*************************/ <BR>function MainProgram(numList){ <BR>var sort = new Sort(numList); <BR>var sortedList = sort.getSortedList(); <BR>if(sortedList == null) <BR>document.getElementById('result').innerHTML = "WRONG INPUT"; <BR>else{ <BR>document.getElementById('result').innerHTML = sortedList.join(','); <BR>} <BR>} <br><br>/**************Sort Class***********************/ <BR>var Sort = function(list){ <BR>this.resultList = list; <BR>}; <br><br>Sort.prototype.Partition = function(start,end){ <BR>var baseValue = this.resultList[start]; <BR>var basePos = start; <BR>for(var j = start + 1;j <= end;j++){ <BR>if(baseValue > this.resultList[j]){ <BR>basePos++; //move the base position <BR>this.Swap(basePos,j); <BR>} <BR>} <BR>// move the base value to the correct place , before are smaller , behind are bigger <BR>this.Swap(start,basePos); <BR>return basePos; <BR>} <br><br>Sort.prototype.QuickSort = function(start,end){ <BR>if(start < end){ <BR>var basePos = this.Partition(start,end); <BR>this.QuickSort(start,basePos - 1); <BR>this.QuickSort(basePos + 1, end); <BR>} <BR>}; <br><br>Sort.prototype.Swap = function(pos1,pos2){ <BR>var temp = this.resultList[pos1]; <BR>this.resultList[pos1] = this.resultList[pos2]; <BR>this.resultList[pos2] = temp; <BR>} <br><br>Sort.prototype.getSortedList = function(){ <BR>this.QuickSort(0,this.resultList.length - 1); <BR>return this.resultList; <BR>}; <br><br> Quick Sort SORTED LIST: 输出: