Latest web development tutorials

C Exercise Example 37 - Sort

100 cases of classic C language 100 cases of classic C language

Title: 10 Number of sorts.

Program Analysis: You can use selection method, that is, from 9 comparison process, select a minimal exchange with the first element, the next and so on, that is, with the second element and after eight compared and exchanged.

Source Code:

//  Created by www.w3big.com on 15/11/9.
//  Copyright © 2015年 本教程. All rights reserved.
//

#include<stdio.h>
#define N 10
int main()
{
    int i,j,a[N],temp;
    printf("请输入 10 个数字:\n");
    for(i=0;i<N;i++)
        scanf("%d",&a[i]);
    for(i=0;i<N-1;i++)
    {
        int min=i;
        for(j=i+1;j<N;j++)
            if(a[min]>a[j]) min=j;
        if(min!=i)
        {
            temp=a[min];
            a[min]=a[i];
            a[i]=temp;
        }
    }
    printf("排序结果是:\n");
    for(i=0;i<N;i++)
        printf("%d ",a[i]);
    printf("\n");
    return 0;
}

The above example output is:

请输入 10 个数字:
23 2 27 98 234 1 4 90 88 34
排序结果是:
1 2 4 23 27 34 88 90 98 234 

100 cases of classic C language 100 cases of classic C language