Fast sorting (solving small file Division)

Source: Internet
Author: User
# Include <iostream> # include <cstdlib> # define M 20 using namespace std; static int count_insert = 0; static int count_partion = 0; void swap (int & small, int & big) {int temp = small; small = big; big = temp;}/* | insert sort in brief: | cur = 1-> right is the part to be sorted, pre indicates the sorted part. | First store the first position element arr [cur] into tmp, then compare the arr [pre] and arr [cur], | if arr [cur] <arr [pre] is to be sorted, arr [pre + 1] = arr [pre] is shifted. | the purpose of the shift is to shift small elements, here, arr [cur] is placed in the proper position of the sorted part. | in this way, each arr [cur] will be overwritten by arr [pre, this is why tmp = arr [cur] was just started | then place tmp at the location of arr [pre] */void insert_sort (int arr [], int left, int right) {int tmp, cur, pre; for (cur = 1; cur <right; cur ++) {pre = cur-1; tmp = arr [cur]; while (tmp <arr [pre] & pre> = 0) {arr [pre + 1] = ar R [pre]; pre --;} arr [pre] = tmp;} count_insert + = 1;} int partion (int arr [], int left, int right) {int base = arr [right]; int I = left-1; for (int j = left; j <right; j ++) {if (arr [j] <base) {I + = 1; if (arr [j]! = Arr [I]) swap (arr [j], arr [I]);} swap (arr [right], arr [I + 1]); count_partion + = 1; return I + 1;}/* | if the length of the sub-file after division is less than 20, insert and sort the sub-files, | otherwise, quick sorting */void quick_sort (int arr [], int left, int right) {if (left <right) {if (right-left) <= M) insert_sort (arr, left, right); else {int sec = partion (arr, left, right); quick_sort (arr, left, sec-1); quick_sort (arr, sec + 1, right) ;}}int main () {const int size = 500; int s [size]; srand (0); for (int I = 0; I <size; I ++) s [I] = rand () % 200; quick_sort (s, 0, size-1); for (I = 0; I <size; I ++) cout <s [I] <"; cout <endl; cout <" call insert_sort "<count_insert <" times "<endl; cout <"call partion_sort" <count_partion <"times" <endl; cin. get (); return 0 ;}

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.