简述:
用到javascript的排序一组数字,js没有直接的数字比较的函数可以调用,所以自己写了一个快速排序
知识点:
1. 正则表达式提取正负数字的string
2. str 转数字 放回列表
3. js的对象Sort类的声明及定义
4. Sort类构造函数、成员函数定义方式(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>
输出:
快速排序,js排序
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 群星2013-青春缤纷辑压箱宝大公开3CD2[新加坡限量版][WAV整轨]
- 林育群.2013-BalladShow(日本版)【环球】【WAV+CUE】
- 陈加洛.1992-痛到感觉不到【宝丽金】【WAV+CUE】
- 群星.2023-宿命之敌电视剧原声带【韶愔音乐】【FLAC分轨】
- 東京事変-大発見[FLAC+CUE]
- 椎名林檎-三文ゴシップ[FLAC+CUE]
- 2024年08月04日
- 裘德《裘德「最后的水族馆」演唱会LIVE》[320K/MP3][228.89MB]
- 裘德《裘德「最后的水族馆」演唱会LIVE》[24bit 48kHz][FLAC/分轨][2.08G]
- 基因三重奏《如果你什么都不说 音乐会现场录音》[320K/MP3][145.37MB]
- 孟庭苇.1996-月亮说话(2020环球24KGOLD限量版)【上华】【WAV+CUE】
- 群星.1997-新艺宝优质音响系列·国语精选监听版【新艺宝】【WAV+CUE】
- 阿桑.2005-寂寞在唱歌(星外星引进版)【华研国际】【WAV+CUE】
- 基因三重奏《如果你什么都不说 音乐会现场录音》[FLAC/分轨][287.43MB]
- 蔡题谦《我爱你,却依然要看你走》[320K/MP3][88.65MB]