Easy Tutorial
❮ C Function Getc C Function Pow ❯

C Exercise Example 37 - Sorting

C Language Classic 100 Examples

Topic: Sort 10 numbers.

Program Analysis: Use the selection method, which involves comparing the last 9 elements to find the smallest and swap it with the first element. Repeat the process by comparing the second element with the next 8 elements and swapping if necessary.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include<stdio.h>
#define N 10
int main()
{
    int i,j,a[N],temp;
    printf("Please enter 10 numbers:\n");
    for(i=0;i&lt;N;i++)
        scanf("%d",&a[i]);
    for(i=0;i&lt;N-1;i++)
    {
        int min=i;
        for(j=i+1;j&lt;N;j++)
            if(a[min]>a[j]) min=j;
        if(min!=i)
        {
            temp=a[min];
            a[min]=a[i];
            a[i]=temp;
        }
    }
    printf("Sorted result is:\n");
    for(i=0;i&lt;N;i++)
        printf("%d ",a[i]);
    printf("\n");
    return 0;
}

The output of the above example is:

Please enter 10 numbers:
23 2 27 98 234 1 4 90 88 34
Sorted result is:
1 2 4 23 27 34 88 90 98 234

C Language Classic 100 Examples

❮ C Function Getc C Function Pow ❯