<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>排序</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://cdn.bootcss.com/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="inp_num" value="" id="num"/>
<p>输入的数组:{{inp_num}}</p>
<p id="result"></p>
<button id="btn">排序</button>
</div>
<script>
$('#btn').on('click',function(){
var input = document.getElementById("num");
var arr = input.value.split(",");//当arr为input的value值时,排序出现问题,问题在于split()分割出来的是字符串,不是数字,不能直接比较
//var arr = [8,4,6,12];//当arr为自定义数组时,排序没问题
//alert(arr[2]);
for(var m=0,len=arr.length;m<len;m++){//把字符串数组转换为数字数组
var item = Number(arr[m]);
arr[m] = item;
//alert(arr[m]);
}
function bubbleSort(arr) {
var i = arr.length, j;
var temp;
while (i > 0) {
for (j = 0; j < i-1 ; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
i--;
}
return arr;
}
var arrSorted = bubbleSort(arr);
console.log(arrSorted);
res = arrSorted.join(',');
$('#result').html('排序后的结果:'+res);
});
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
//$scope.inp_num= arr;
})
</script>
</body>
</html>
冒泡排序将输入框的数字排序(结合angular.js)
最新推荐文章于 2025-04-03 22:42:37 发布