面试常见算法一

  // 快速排序
  function fastSortingArray(array, left, right) {
        if (left >= right) {
            return
        }
        var i = left;
        var j = right;
        let key = array[left];

        while (i < j) {
            while (i < j & key <= arr[j]) {
                j--;
            }
            swap(array, i, j);

            while (i < j & key >= arr[i]) {
                i++;
            }
            swap(array, i, j);
        }

        fastSortingArray(array, left, i - 1)
        fastSortingArray(array, i + 1, right)
    }


    // 选择排序
    function selectionSort(array) {
        for (let i = 0; i < array.length - 1; i++) {
            for (let j = i + 1; j < array.length; j++) {
                if (array[i] > array[j]) {
                    swap(array, i, j)
                }
            }
        }
    }

    function swap(array, left, right) {
        let temp = array[left];
        array[left] = array[right];
        array[right] = temp;
    }


    // 二分查找
    function twoPointLookup(array, key) {
        let lower = 0;
        let upper = array.length - 1;
        let middle = 0;

        while (lower < upper) {
            middle = parseInt((lower + upper) / 2);
            if (key == array[middle]) {
                console.log(middle);
                return middle;
            }
            if (key < array[middle]) {
                upper = middle - 1
            }
            if (key > array[middle]) {
                lower = middle + 1;
            }
        }
    }

    // 第二小的值
    function secondValue(array) {
        let min1 = 0;
        let min2 = 0;

        if (array[0] > array[1]) {
            min1 = array[1];
            min2 = array[0];
        } else {
            min1 = array[0];
            min2 = array[1];
        }

        for (let index = 2; index < array.length; index++) {
            if (array[index] < min1) {
                min2 = min1;
                min1 = array[index];
            }

            if (array[index] > min1 & array[index] < min2) {
                min2 = array[index];
            }
        }
        console.log(min2);
        return min2;
    }

    // 合并有序数组
    function mergeArrays(arr1, arr2, arr3, n1, n2) {
        let i = 0, j = 0, k = 0;

        while (i < n1 & j < n2) {
            if (arr1[i] < arr2[j]) {
                arr3[k++] = arr1[i++];
            } else {
                arr3[k++] = arr2[j++];
            }
            console.log(i, j);
            
        }

        while (i < n1){
            arr3[k++] = arr1[i++];
        }
            
        while (j < n2){
            arr3[k++] = arr2[j++];
        }
           
        console.log(arr3);
        
    }

你可能感兴趣的:(面试常见算法一)