Sort algorithm-Exchange sort (JavaScript)

Source: Internet
Author: User

thought : 22 comparison, once the discovery does not meet the order requirements of the exchange, know that the entire sequence satisfies the ordering requirements.

Typical: bubble sort and quick sort.

Bubble Sort

thought: compare adjacent two, reverse the exchange, each order will be the largest ' sinking ' or the smallest ' float '.

function Bubblesort (arr) {Const LEN = Arr.length;let temp = 0;for (let i=0;i<len-1;i++) {for (let j=0;j<len-i-1;j++) { if (arr[j]>arr[j+1]) {temp = Arr[j];arr[j] = arr[j+1];arr[j+1] = temp;}}} return arr;}

Complexity of Time:

Best case: Positive order. It takes only a single trip to sort, make n-1 comparisons, and not move records.

Worst case: reverse. As long as the n-1 sequencing, the comparison is N^2/2, the number of moves 3N^2/2.

So the complexity of Time is O (n^2).

Complexity of space:

The space Complexity is O (1)when a secondary space is required to do the staging record only when two records are exchanged.

Characteristics:

1, is a stable sort.

2, can be used for chain storage structure.

3, the number of mobile records more, the average time performance of the algorithm than the direct insertion sorting difference. This algorithm is not suitable when the initial record is unordered and N is large.

Quick Sort

Poke: here

Sort algorithm-Exchange sort (JavaScript)

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.