js基础算法复习

var util = util || {};
!(function (t) {
    if (!util.binarySearch) {
        Object.assign(util, t());
    }
}(function () {
    /**
     * 二分查找
     * @param arr  有序数组
     * @param item 查找项
     * @returns {*}
     */
    function binarySearch(arr, item) {
        let low = 0;
        let high = arr.length - 1;
        while (low <= high) {
            let mid = Math.floor((low + high) / 2);
            let guess = arr[mid];
            if (guess === item) return mid;
            if (guess > item) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return null;
    }

    /**
     *  查找数组最小值得index
     * @param arr 无序数组
     * @returns {number}
     */
    function findMinIndex(arr) {
        let minItem = arr[0];
        let minIndex = 0;
        const len = arr.length;
        for (let i = 1; i < len; i++) {
            const item = arr[i];
            if (item < minItem) {
                minItem = item;
                minIndex = i;
            }
        }
        return minIndex;
    }

    /**
     * 简单排序
     * @param arr  无序数组
     * @returns {Array}
     */
    function selectSort(arr) {
        const _arr = [];
        const len = arr.length;
        for (let i = 0; i < len; i++) {
            const minIndex = findMinIndex(arr);
            _arr.push(...arr.splice(minIndex, 1));
        }
        return _arr;
    }

    /**
     * 冒泡排序
     * @param arr  无序数组
     * @returns {*}
     */
    function bubbleSort(arr) {
        const len = arr.length - 1;
        for (let i = 0; i < len; i++) {
            for (let j = 0; j < len; j++) {
                if (arr[j] > arr[j + 1]) {
                    const temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }


    /**
     * 快速排序
     * @param arr
     * @returns {*}
     */
    function quickSort(arr) {
        const len = arr.length;
        if (len < 2) return arr;
        // 基准值选择中间的数 减少递归次数
        const pivot = arr.splice(Math.floor(len / 2), 1)[0];
        const less = [];
        const greater = [];
        for (let i = 0; i < arr.length; i++) {
            if (arr[i] < pivot) {
                less.push(arr[i]);
            } else {
                greater.push(arr[i]);
            }
        }
        return [...quickSort(less), pivot, ...quickSort(greater)];
    }

    return {binarySearch, selectSort, bubbleSort, quickSort};
}));
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>django-websocket</title>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="./node_modules/pako/dist/pako.min.js"></script>
    <script src="./arithmetic.js"></script>
    <script type="text/javascript">//<![CDATA[
    $(function () {
//        function cnn() {
//            if (window.s) {
//                window.s.close()
//            }
//            /*创建socket连接*/
//            var socket = new WebSocket("ws://127.0.0.1:8001");
//            socket.onopen = function () {
//                console.log('WebSocket open');//成功连接上Websocket
//            };
//            socket.onmessage = function (e) {
//                const str =  pako.inflate(e.data, { to: 'string' });
//                console.log(`字符长度:${str.length},接收时间:${new Date().getTime()}`);//打印出服务端返回过来的数据
//                $('#messagecontainer').prepend('<p>' + str + '</p>');
//            };
//            // Call onopen directly if socket is already open
//            if (socket.readyState == WebSocket.OPEN) socket.onopen();
//            window.s = socket;
//        }
//        cnn();
//        $('#connect_websocket').click(function () {
//            cnn();
//        });
//        $('#send_message').click(function () {
//            //如果未连接到websocket
//            if (!window.s) {
//                alert("websocket未连接.");
//            } else {
//                window.s.send($('#message').val());//通过websocket发送数据
//            }
//        });
//        $('#close_websocket').click(function () {
//            if (window.s) {
//                window.s.close();//关闭websocket
//                console.log('websocket已关闭');
//            }
//        });

        /**
         * 随机数获取
         * @param min
         * @param max
         * @returns {number}
         */
        function getRandomNumFun(min, max) {
            min = min || 0;
            max = max || 10;
            return Math.floor(Math.random() * (max - min + 1) + min);
        }
        const test = [];
        const test2 = [];
        for (let i = 0; i < 10000; i++) {
            test.push(i * 2);
            const item = getRandomNumFun(1, 10000);
            test2.push(item)
        }

        $('#binarySearch').prepend('<p>数据位置length:' + util.binarySearch(test, 198) + '</p>');

        /**
         * 简单排序
         */
        const selectSortArr = [...test2];
        const selectSortTimeStart = new Date().getTime();
        const selectSortArr1 = util.selectSort(selectSortArr);
        const selectSortTimeEnd = new Date().getTime();
        /**
         * 冒泡排序
         */
        const bubbleSortArr = [...test2];
        const bubbleSortTimeStart = new Date().getTime();
        const bubbleSortArr1 = util.bubbleSort(bubbleSortArr);
        const bubbleSortTimeEnd = new Date().getTime();
        /**
         * 快速排序
         */

        const quickSortArr = [...test2];
        const quickSortTimeStart = new Date().getTime();
        const quickSortArr1 = util.quickSort(quickSortArr);
        const quickSortTimeEnd = new Date().getTime();

        $('#selectSort').prepend('<p>简单排序耗时:' + (selectSortTimeEnd - selectSortTimeStart) + '</p>');
        $('#bubbleSort').prepend('<p>冒泡排序耗时:' + (bubbleSortTimeEnd - bubbleSortTimeStart) + '</p>');
        $('#quickSort').prepend('<p>快速排序耗时:' + (quickSortTimeEnd - quickSortTimeStart) + '</p>');
    });


    </script>
</head>
<body>
    <br>
    <input type="text" id="message" value="user1"/>
    <button type="button" id="connect_websocket">连接 websocket</button>
    <button type="button" id="send_message">发送 message</button>
    <button type="button" id="close_websocket">关闭 websocket</button>
    <h1>Received Messages</h1>
    <div id="messagecontainer"></div>
    <h2>二分查找</h2>
    <div id="binarySearch"></div>
    <h2>排序</h2>
    <div id="selectSort"></div>
    <div id="bubbleSort"></div>
    <div id="quickSort"></div>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值