JavaScript implementation of bubble sort algorithm

Source: Internet
Author: User

As one of the classic sorting algorithms, bubbling sorting also has several implementations in JavaScript.

Temporary variables are declared in some of the most common implementations, and in other implementations that do not have to declare temporary variables, they may only support numeric arrays or string arrays (either).

Here are two implementations of "No need to declare temporary variables" and "apply to numeric arrays and string arrays."

Version ES5:

vararr = [5, 25, 2, 53, 22, 10];functionBubblesort (arr) { for(varj = 1, len = arr.length; J < Len; J + +){         for(vari = 0; i < len-j; i++) {            if(Arr[i] > arr[i + 1]) {arr[i+ 1] = [Arr[i], arr[i] = arr[i + 1]][0]; Execution Order}}}returnarr;} Console.log (Bubblesort (arr). toString ()); //' 2,5,10,22,25,53 '

Important: Before Arr[i + 1] is re-assigned, Arr[i] has been re-assigned, and its original value has been saved to the 0 index position of the array before arr[i] is re-assigned to the value.

Version ES6:

Let arr = [' Root ', ' Harold ', ' sameen ', ' John '= (arr) + =    {for (Let j = 1, len = Arr.leng Th J < Len; J + +)        {for (let i = 0; i < len-j; i++) {            if (Arr[i] > arr[i + 1 ]) {                + 1]] = [Arr[i + 1], arr[i]];//Deconstruction            }        }}return//  ' Harold,john,root,sameen '

Important: Understand the new deconstructed assignment expression ECMAScript 6.

The end

JavaScript implementation of bubble sort algorithm

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.