你要求里的关键是要保持arr1不变,所以需要先将arr1复制一份进行处理。
<script>
function sort(arrin, k)
{
var arr = arrin.slice(0)
for (var i = 0i <arr.lengthi ++)
{
for (var j = ij <arr.lengthj ++)
{
if (arr[j][k] <arr[i][k])
{
var tmp = arr[j]
arr[j] = arr[i]
arr[i] = tmp
}
}
}
return arr
}
var arr1 =[["abc",0],["ryd",1],["zuyeute",3],["mvzxv",2]]
var arr2 = sort(arr1, 0)
var arr3 = sort(arr1, 1)
</script>
<script type="text/javascript">var count = 0 //循环计数器
var jicount = 0 //奇数计数器
var oucount = 0 //偶数计数器
var arr = new Array() //储存随机数数组
var jishu = new Array() //储存奇数数组
var oushu = new Array() //储存偶数数组
while(count <10){//为奇偶数组赋值
arr[count] = (Math.round((Math.random()*9)+1))
if(arr[count]%2==1){
jishu[jicount] = arr[count]
jicount++
}else{
oushu[oucount] = arr[count]
oucount++
}
count++
}
document.write(jishu.sort(function(a,b){return a-b})) //奇数数组排序输出
document.write("<br />")
document.write(oushu.sort(function(a,b){return a-b})) //偶数数组排序输出
</script>
有一点注释,看不懂再问我。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
<head>
<title>冒泡排序</title>
<script type="text/javascript">
var bubbleSort = function (array) {//从后向前
if(!(array instanceof Array)) {
return
}
var n = array.length
for(var i = 0i <n-1i++) {
for(var j = n-1j >ij--) {
var a = array[j], b = array[j-1]
if(a <b) {
array[j-1] = a
array[j] = b
}
}
}
}
var bubbleSort2 = function(array) { //从前到后
if(!(array instanceof Array)) {
return
}
var n = array.length
for(var i = 0i <ni++) {
for(var j = 0j<j-i-1j++) {
var a = array[j], b= array[j+1]
if (a >b){
array[j] = b
array[j+1] = a
}
}
}
}
</script>
</head>
<body>
<p>输入实例:1,2,3,123,3,2,13123,3,6,7,1</p>
<input type="text" autocomplete="on" id="enterArray" style="width:400pxheight:40pxline-height:40pxpadding:2pxfont-size:16px" />
<button id="submit">排序</button>
<div id="show" style="font-weight:boldfont-size:20pxmargin-top:30pxcolor:#f90"></div>
<script type="text/javascript">
document.getElementById('submit').onclick = function(event) {
var arr = stringToArray(document.getElementById('enterArray').value)
document.getElementById('show').innerHTML = "排序前:" + arr
bubbleSort(arr)
document.getElementById('show').innerHTML += "<br />排序后:" + arr
}
function stringToArray(str) {
var array = []
var arr = str.split(',')
for(var i = 0i<arr.lengthi++) {
array.push(parseFloat(arr[i]))
}
return array
}
</script>
</body>
</html>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)