Several common sorting algorithms

Source: Internet
Author: User

[Cpp] // classic bubble sort void BubbleSort (int arr [], int n) {int I = 0, j = 0; for (I = 0; I <n; I ++) for (j = 0; j <n-1-I; j ++) {if (arr [j]> arr [j + 1]) {arr [j] = arr [j] ^ arr [j + 1]; arr [j + 1] = arr [j] ^ arr [j + 1]; arr [j] = arr [j] ^ arr [j + 1] ;}} exchange two data types. Temporary variables can be used, the following two methods can also be used: a = a ^ B; B = a ^ B; a = a ^ B; or a = a + B; B = a-B; a = a-B; [cpp] // select the sort void SelectSort (int arr [], int n) {int I, j; int min; for (I = 0; I <n-1; I ++) {int index = 0; min = arr [I]; for (j = I + 1; j <n; j ++) // finds out the minimum vertex in the I + 1-n unordered zone and exchanges with arr [I] {if (arr [j] <min) {min = arr [j]; index = j ;}} if (index! = 0) // indicates that the disordered zone has an element smaller than arr [I] {arr [I] = arr [I] ^ arr [index]; arr [index] = arr [I] ^ arr [index]; arr [I] = arr [I] ^ arr [index] ;}} I feel much better than the bubble method [cpp] // fast Sorting Algorithm void QuickSort (int arr [], int n) {int I = 0, j = n-1; int key = arr [0]; int index = 0; if (n <= 1) return; while (I <j) {// search for while (j> I & arr [j]> key) j --; if (j = I) break; else {arr [I ++] = arr [j]; index = j ;}// search for while (I <j & arr [I] <key) I ++; if (I = j) break; else {arr [j --] = arr [I]; index = I ;}} QuickSort (arr, index ); quickSort (arr + index + 1, n-1-index );}

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.