Fast sorting and heap sorting

Source: Internet
Author: User

Fast sorting and heap sorting

1. Quick sorting

Fast sorting is an unstable Sorting Algorithm with an average time complexity of O (nlgn ). Fast sorting uses partition () for sorting. Partition () has two implementation forms: (1) Use two pointers, one header pointer and one tail pointer, and sort by exchanging the number indicated by the head and tail pointer; (2) the first and second pointers traverse from left to right at the same time. If the number of the first pointer is smaller than that of the main component, the second pointer shifts one bit to the right and then exchanges them. The Partition method can also be used in many places.

// Quicksort time complexity O (n ^ 2), unstable sorting void quicksort (int array [], int left, int right) {if (left <right) {int I = left, j = right; int x = array [left]; while (I <j) {while (I <j & array [j]> = x) j --; if (I <j) array [I ++] = array [j]; while (I <j & array [I] <= x) I ++; if (I <j) array [j --] = array [I];} array [I] = x; quicksort (array, left, J-1); quicksort (array, j + 1, right );}}

2. Heap sorting

Heap sorting is an unstable Sorting Algorithm with an average time complexity of O (nlgn ).

// Heap sorting void heap_build (int array [], int I, int len) {int left = 2 * I; int right = 2 * I + 1; int max = I; if (left <len & array [left]> array [max]) max = left; if (right <len & array [right]> array [max]) max = right; if (max! = I) {swap (array [max], array [I]); heap_build (array, max, len) ;}} void heap_sort (int array [], int n) {int I; for (I = n/2; I> = 0; I --) {heap_build (array, I, n) ;}for (I = n-1; I >= 1; I --) {swap (array [0], array [I]); n = n-1; heap_build (array, 0, n );}}

Stable sorting algorithms: insert sorting directly, Bubble sorting, Merge Sorting, and base sorting.



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.