簡述: 用到javascript的排序一組數字,js沒有直接的數字比較的函數可以調用,所以自己寫了一個快速排序知識點: 1. 正規表示式提取正負數字的string 2. str 轉數字放回列表3. js的物件Sort類別的宣告及定義4. Sort類別建構子、成員函數定義方式(prototype) 5. 快速排序算法代碼: 複製代碼 代碼如下: . Quick Sort <BR>/************從輸入取得數字*************/ <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>/*****************主要的*************************/ <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>/************排序類別*************************/ <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 biggerthis <s>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>this>this>this>this> .resultList[pos2] = temp; <BR>} <BR><br>Sort.prototype.getSortedList = function(){ <br>this.QuickSort(0,this.resultList.length - 1); this.resultList; <BR>}; <BR><BR> Quick Sort SORTED LIST: