JavaScript实现快速排序(自已编写)
简述:
用到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>
输出:

img onload事件绑定各浏览器均可执行
在需要对img进行onload事件绑定的时候,一般大家都会想到用常规的方法进行事件绑定,如下:!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/
javascript的原生方法获取数组中的最大(最小)值
获取一个数组中的最大(最小)值的最简单的方法,就是对数组进行一次遍历,通过比较,找到其最大(最小)值。但是其实在javascript的原生方法中,
mailto的使用技巧分享
mailto用法如何使用mailto?1)基本用法ahref=mailto:sample@163.comsendemail/a或者formaction="mailto:sample@163.com"/formmailto后跟的是收信人。可使用参数列表to收信人suject
标签:数组,绑定,方法,收信人,函数