Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript中的排序算法 #13

Open
WarpPrism opened this issue Nov 13, 2016 · 0 comments
Open

JavaScript中的排序算法 #13

WarpPrism opened this issue Nov 13, 2016 · 0 comments

Comments

@WarpPrism
Copy link
Owner

三种常用的简单排序算法(JavaScript描述),默认从小到大排列,下面是code:

function quickSort(arr) {
    if (Object.prototype.toString.call(arr) != '[object Array]') {
        return 'Error: Not Array Object';
    }
    if (arr.length <= 1) {
        return arr;
    }

    var middle = Math.floor(arr.length / 2);
    var pivot = arr.splice(middle, 1)[0];
    var left = [], right = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] < pivot) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }
    return (quickSort(left).concat([pivot], quickSort(right)));
}
function selectSort(arr) {
    if (Object.prototype.toString.call(arr) != '[object Array]') {
        return;
    }
    if (arr.length <= 1) return arr;

    for (var i = 0; i < arr.length - 1; i++) {
        var min = i;
        for (var j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[min]) {
                min = j;
            }
        }
        var temp = arr[min];
        arr[min] = arr[i];
        arr[i] = temp;
    }
    return arr;
}
function bubbleSort(arr) {
    if (Object.prototype.toString.call(arr) != '[object Array]') {
        return;
    }
    if (arr.length <= 1) return arr;

    for (var i = 0; i < arr.length - 1; i++) {
        for (var j = i; j < arr.length; j++) {
            if (arr[j + 1] < arr[j]) {
                // swap
                var temp = arr[j + 1];
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}

对于Javascript来说,推荐快速排序算法,其执行效率比较高。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant