JavaScript實現(xiàn)快速排序(自已編寫)
更新時間:2012年12月19日 11:13:15 作者:
用到javascript的排序一組數(shù)字,js沒有直接的數(shù)字比較的函數(shù)可以調用,所以自己寫了一個快速排序,需要的朋友可以了解下
簡述:
用到javascript的排序一組數(shù)字,js沒有直接的數(shù)字比較的函數(shù)可以調用,所以自己寫了一個快速排序
知識點:
1. 正則表達式提取正負數(shù)字的string
2. str 轉數(shù)字 放回列表
3. js的對象Sort類的聲明及定義
4. Sort類構造函數(shù)、成員函數(shù)定義方式(prototype)
5. 快速排序算法
代碼:
復制代碼 代碼如下:
<!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>
輸出:
相關文章
javascript實現(xiàn)用戶必須勾選協(xié)議實例講解
這篇文章主要介紹了javascript實現(xiàn)用戶必須勾選協(xié)議實例講解,寫頁面的時候經(jīng)常會用到,有感興趣的同學可以學習下2021-03-03
javascript中數(shù)組array及string的方法總結
本文結合自己的使用經(jīng)驗,給大家總結了javascript中數(shù)組array及string的使用方法,這里推薦給有需要的小伙伴。2014-11-11
Javascript數(shù)組循環(huán)遍歷之forEach詳解
本篇文章主要介紹了Javascript 數(shù)組循環(huán)遍歷之forEach詳解,對學習forEach有很好的幫助,有需要的可以了解一下。2016-11-11
document 和 document.all 分別什么時候用
document 和 document.all 分別什么時候用...2006-09-09

