Bubble sort, select sort, insert sort, and bubble sort

Source: Internet
Author: User

Bubble sort, select sort, insert sort, and bubble sort

# Include <stdio. h> int swap (int * a, int * B) {int t = * a; * a = * B; * B = t;}/* principle of Bubble Sorting: each time, the two adjacent numbers are compared in an unordered queue, and the decimal number is switched to the front. The number is compared one by one until the maximum number is moved to the end. The maximum number of remaining N-1 continues to be compared, move the number of times to the second to last. According to this rule, until the comparison ends. The code for Bubble Sorting is as follows: */void bubble_sort (int a [], int n) {int I, j; for (I = 0; I <n-1; ++ I) for (j = 0; j <n-i-1; ++ j) {if (a [j]> a [j + 1]) swap (& a [j], & a [j + 1]) ;}/ * principle of sorting: "select" the minimum value in the unordered queue and put it at the end of the ordered queue, and remove this value from the unordered Queue (the specific implementation is slightly different ). Code for sorting: */void selection_sort (int a [], int n) {int I, j; int min; for (I = 0; I <n; ++ I) {min = I; for (j = I + 1; j <n; ++ j) {if (a [j] <a [min]) min = j;} if (min! = I) swap (& a [min], & a [I]) ;}/ * principle of insertion sorting: always define the first element as ordered, insert elements one by one into an ordered arrangement. The feature is to constantly move the data, leave an appropriate location empty, and put the elements to be inserted into it. The code for inserting sorting is as follows: */void insertion_sort (int a [], int n) {int I, j; for (I = 1; I <n; ++ I) {int A = a [I]; j = I-1; while (j> = 0 & a [j]>) {a [j + 1] = a [j]; j --;} a [j + 1] = A ;}} int main (int argc, char * argv []) {int a [] = {5, 6, 7, 1, 2, 3}; // bubble_sort (a, 6); // selection_sort (a, 6); insertion_sort (a, 6 ); int I; for (I = 0; I <sizeof (a)/sizeof (int); ++ I) {printf ("% d", a [I]);} printf ("\ n"); 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.