The array bubble sort of JS interview frequently test

Source: Internet
Author: User

Array Ordering of JS

Give an array of numbers that do not need to let the write bubble sort:

Analysis: Bubble sort refers to the number of the first item compared to the second item, the first big words of the two swap positions, if the second big words will be the same position;

After comparing the second third item, the comparison result repeats the previous step; (Inner for Loop)

The first comparison is done at the beginning of the second item in the previous link; (Outer for Loop)

Only until the end of the last second item is completed;

An example of an array of arr = [3,56,4,1,34,78,23,59,66,42];

        Bubble sort function Arrsort (arr) {var len = arr.length;for (var i = 0; I <len; i++) {//determines the number of cycles required for (var j = 0; j < Len-1-i; J + +) {if (arr[j]>arr[j+1]) {//adjacent two items for comparison var nu = arr[j+1];arr[j+1] = arr[j];arr[j]= nu;}}} Console.log (arr);} Arrsort (arr);    

But this two for loop is quite a memory-intensive operation if the amount of data is large, because each time the for loop is completed to find a maximum number in the last position,

The outer loop does not have a coarse cycle to the last few to re-cycle, in order to save the number of cycles in each of the last time for the loop to change the location of the mark;

2. Improved bubble sorting:

function ArrSort2 (arr) {var i = Arr.length-1;while (i>0) {console.log (i)///Here the index of each data position of arr (minus the first item 0), var pos = 0  0;for (Var j=0;j<i;j++) {if (arr[j]>arr[j+1]) {Pos=j;var Nu = arr[j+1];arr[j+1] = arr[j];arr[j]= nu Each time the loop is positioned;    }} i=pos;//the location of the last interchange;} console.log (arr); } arrSort2 (arr);

Save some unnecessary loops and increase the speed of operation!

The array bubble sort of JS interview frequently test

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.