Javascript的冒泡排序和二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script type="text/javascript">
    /**
     * js 冒泡排序
     */
    //var  numArr = [-3,-10,0,32,9,3,23];
    var  numArr = [-1,0,3,23,34,];
    var flag = false;
    for(var i = 0; i < numArr.length -1; i++) { //控制比较多少轮
        document.writeln("比较多少轮:" + (i+1) + "<br />");
        for(var j = 0; j < numArr.length - i -1;j++) {//控制每轮比较的次数
            if(numArr[j] > numArr[j+1]) {
                //交换
                var temp = numArr[j];
                numArr[j] = numArr[j+1];
                numArr[j+1] = temp;
                flag = true;
            }
        }
        if(flag) {
            flag = false;
        else {
            //禁止循环,这样做的好处:当数组有序时就不要在循环了
            break;
        }
                             
    }
    document.writeln(numArr);
</script>




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<script type="text/javascript">
    /**
     * JS的二分查找
     * 1.注意事项:二分查找必须针对的是有序的数组,不是有序的数组不能使用二分查找法
     * 2.思路:首先找到数组的中间数(midVal),和你要查找的数(findVal)进行比较,如果
     * midVal > findVal ,则说明在数组的左边,就把该数组二分(就只在左边查找)
     */
                
    function binarySearch(arr,findVal,leftIndex,rightIndex) {
        //防止无穷递归
        if(leftIndex > rightIndex) {
            document.writeln("找不到");
            return;
        }
        //找到中间这个值
        var midIndex = Math.floor((leftIndex + rightIndex)/2);
        var midVal = arr[midIndex];
        //比较
        if(midVal > findVal) {
            //在左边查找
            binarySearch(arr,findVal,leftIndex,midIndex - 1);
        else if(midVal < findVal) {
            //在右边查找
            binarySearch(arr,findVal,midIndex+1,rightIndex);
        else {
            document.writeln("找到了,位置为:" + midIndex);
            return;
        }
    }
    var arr = [1,2,5,67,89,90];
    binarySearch(arr,3,0,arr.length -1);
</script>

==================================================================================

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<script type="text/javascript">
    /*数组的简单行列倒置*/
    var arr = [[2,4,6,8],[1,3,5,9],[9,7,4,2]];
            
    //定义一个新的数组
    var arr2 = [];
    //初始化新数组的行数,我认为该数组是规则的,并初始化
    for(var i = 0; i < arr[0].length; i++) {
        arr2[i] = [];
    }
            
    //动态的添加新数据,遍历旧数据
    for(var i=0; i < arr.length; i++) {
        for(var j=0; j < arr[i].length; j++) {
            arr2[j][i] = arr[i][j];
        }
    }
            
    //遍历新数组,显示数据
    for(var i=0; i < arr2.length; i++) {
        for(var j=0; j < arr2[i].length; j++) {
            document.writeln(arr2[i][j] + "&nbsp;");
        }
        document.writeln("<br />");
    }
            
</script>


     本文转自韩立伟 51CTO博客,原文链接:http://blog.51cto.com/hanchaohan/1308498,如需转载请自行联系原作者





上一篇:UVA - 11624 Fire!(多源bfs+双bfs)


下一篇:java插入排序兼编码注意