"JavaScript implementations of sorting algorithms"

Source: Internet
Author: User

Bubble sort

    1. Let compare = (n1, n2) = n1-n2;
    • Let Bubblesort = (arr, cmp = compare) = = {
    • for (Let i = 0; i < arr.length; i++) {
    • for (Let j = i; j > 0; j--) {
    • if (CMP (ARR[J], arr[j-1]) < 0) {
    • [Arr[j], arr[j-1]] = [arr[j-1], arr[j];
    • }
    • }
    • }
    • return arr;
    • };


Insert Sort

    1. Let Insertionsort = (arr) = = {
    • for (Let i = 0; i < a.length; i++) {
    • Let tocmp = Arr[i];
    • for (Let j = i; j > 0 && tocmp < a[j-1]; j--)
    • ARR[J] = a[j-1];
    • ARR[J] = tocmp;
    • }
    • return arr;
    • }


Select sort

    1. var selectionsort = function (arr) {
    • Let I,m,j;
    • for (i =-1; ++i < a.length;) {
    • for (m = j = i; ++j < a.length;) {
    • if (Arr[m] > arr[j]) m = j;
    • }
    • [Arr[m], arr[i]] = [Arr[i], arr[m];
    • }
    • return arr;
    • }


Merge sort

    1. Let MergeSort = (arr) = = {
    • if (Arr.length < 2) return arr;
    • Let middle = parseint (ARR.LENGTH/2),
    • left = Arr.slice (0, middle),
    • right = Arr.slice (middle);
    • Return merge (MergeSort (left), MergeSort (right));
    • }
    • Let merge = (left, right) + = {
    • let result = [];
    • while (Left.length && right.length) {
    • Left[0] <= right[0]?
    • Result.push (Left.shift ()):
    • Result.push (Right.shift ());
    • }
    • while (left.length) Result.push (Left.shift ());
    • while (right.length) Result.push (Right.shift ());
    • return result;
    • }


Quick Sort

    1. Let quicksort = function (arr) {
    • if (arr.length <= 1) return arr;
    • let pivot = Math.floor ((arr.length-1)/2);
    • Let val = Arr[pivot], less = [], more = [];
    • Arr.splice (pivot, 1);
    • Arr.foreach (function (e,i,a) {
    • E < val? Less.push (E): More.push (e);
    • });
    • Return (quicksort (less)). Concat ([Val],quicksort (more))
    • }??


More Java,java interview questions, Java learning http://techfoxbbs.com


"JavaScript implementations of sorting algorithms"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.