排序算法和二分法查找

  • 请填充代码,使mySort()能使传入的参数按照从小到大的顺序显示出来。

function mySort() {
    var tags = new Array();
    for (var i = 0; i < arguments.length; i++) {
        tags.push(arguments[i]);
    }
    tags.sort(function sortNum(a, b) {
        return a - b;
    });
    return tags;
}

var result = mySort(50, 11, 16, 32, 24, 99, 57, 100);
console.info(result);
  • 冒泡排序

function bubbleSort(arr) {
    for (var i = 0; i < arr.length; i++) {
        for (var j = 0; j < arr.length - i; j++) {
            var temp = 0;
            // ">" 从小到大排序
            // "<" 从大到小排序
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}
  • 快速排序

 function quickSort(elements) {
    if (elements.length <= 1) {
        return elements;
    }
    var pivotIndex = Math.floor(elements.length / 2);
    var pivot = elements.splice(pivotIndex, 1)[0];
    var left = [];
    var right = [];
    for (var i = 0; i < elements.length; i++) {
        if (elements[i] < pivot) {
            left.push(elements[i]);
        } else {
            right.push(elements[i]);
        }
    }
    return quickSort(left).concat([pivot], quickSort(right));
}
  • 插入排序

insertSort = function (elements) {
    var i = 1,
        j, step, key, len = elements.length;
    for (; i < len; i++) {
        step = j = i;
        key = elements[j];
        while (--j > -1) {
            if (elements[j] > key) {
                elements[j + 1] = elements[j];
            } else {
                break;
            }
        }
        elements[j + 1] = key;
    }
    return elements;
};
  • 二分查找-递归方法

function binarySearch(arr, key, leftIndex, rightIndex) {
    if (leftIndex > rightIndex) {
        return -1;
    }
    var mid = parseInt((leftIndex + rightIndex) / 2);
    if (arr[mid] == key) {
        return mid;
    } else if (arr[mid] > key) {
        rightIndex = mid - 1;
        return binarySearch(arr, key, leftIndex, rightIndex);
    } else if (arr[mid] < key) {
        leftIndex = mid + 1;
        return binarySearch(arr, key, leftIndex, rightIndex);
    }
}
  • 二分查找-非递归方法

function binarySearch(arr, key) {
    var leftIndex = 0,
        rightIndex = arr.length - 1;
    while (leftIndex <= rightIndex) {
        var mid = parseInt((leftIndex + rightIndex) / 2);
        if (arr[mid] == key) {
            return mid;
        } else if (arr[mid] < key) {
            leftIndex = mid + 1;
        } else if (arr[mid] > key) {
            rightIndex = mid - 1;
        } else {
            return -1;
        }
    }
}

你可能感兴趣的:(排序,javascript)