How js achieves array Bubble sorting and fast sorting _ javascript skills

Source: Internet
Author: User
This article mainly introduces in detail how js achieves array Bubble sorting and fast sorting, interested friends can refer to this article to share with you the implementation principles of js array Bubble sorting and quick sorting. The details are as follows:

1. Bubble Sorting:

Take a single digit from the array and compare it with the last digit. If you want to sort the digits from small to large, put the small one in front and the big one in the back, simply put, it is to swap their locations, so that repeated switching positions can be sorted.

Var arr = [, 21, 63]; function sortA (arr) {for (var I = 0; iarr [j]) {// because the value needs to be exchanged, therefore, the next value will be replaced. We need to save the var index = arr [j]; // The swap value arr [j] = cur; arr [I] = index ;}}return arr ;}// because one loop can only exchange one maximum value, you need to set another for loop.

2. Quick sorting:

Take a value from the middle of the array, and then compare it with the value in the array. If the value is greater than one side, the value is smaller than the other side, and then merge the values, and then compare them.

Var arr = [, 21, 63]; function sortA (arr) {// if there is only one bit, there is no need to compare if (arr. length <= 1) {return arr;} // obtain the index var len = Math. floor (arr. length/2); // intercept the median value var cur = arr. splice (len, 1); // if the value is smaller than the center value, set var left = []; // if the value is greater than, set var right = []; for (var I = 0; iarr [I]) {left. push (arr [I]);} else {right. push (arr [I]) ;}/// through recursion, the previous round of better array merging and comparison again. Return sortA (left). concat (cur, sortA (right ));}

Want to learn

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.