×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to sort array elements in ascending order

To sort an array in ascending order, compare each element and arrange them from the smallest to the largest.

Problem statement

Given an array, write a C program to sort array elements in ascending order.

Example

Input array elements are:
50, 10, 20, 40, 30

Output:
Sorted array elements are:
10, 20, 30, 40, 50

C program to sort array elements in ascending order

In this program, we are reading an array of integers and sorting array elements in ascending order.

/*program to sort array elements in ascending order. */
#include <stdio.h>

/** funtion :   readArray() 
    input   :   arr ( array of integer ), size 
    to read ONE-D integer array from standard input device (keyboard). 
**/
void readArray(int arr[], int size)
{
    int i = 0;

    printf("\nEnter elements : \n");

    for (i = 0; i < size; i++) {
        printf("Enter arr[%d] : ", i);
        scanf("%d", &arr[i]);
    }
}

/** funtion :   printArray() 
    input   :   arr ( array of integer ), size 
    to display ONE-D integer array on standard output device (moniter). 
**/
void printArray(int arr[], int size)
{
    int i = 0;

    printf("\nElements are : ");

    for (i = 0; i < size; i++) {
        printf("\n\tarr[%d] : %d", i, arr[i]);
    }
    printf("\n");
}

void sortArray(int arr[], int size)
{
    int i = 0, j = 0, temp;

    for (i = 0; i < size - 1; i++) {
        for (j = i + 1; j < size; j++) {
            if (arr[i] > arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

int main()
{
    int arr[5];

    readArray(arr, 5);

    printf("\nBefore Sorting");
    printArray(arr, 5);

    sortArray(arr, 5);

    printf("\nAfter Sorting");
    printArray(arr, 5);

    return 0;
}

Output

Enter elements : 
Enter arr[0] : 12 
Enter arr[1] : 10 
Enter arr[2] : 67 
Enter arr[3] : 88 
Enter arr[4] : 10 

Before Sorting 
Elements are : 
	arr[0] : 12 
	arr[1] : 10 
	arr[2] : 67 
	arr[3] : 88 
	arr[4] : 10 

After Sorting 
Elements are : 
	arr[0] : 10 
	arr[1] : 10 
	arr[2] : 12 
	arr[3] : 67 
	arr[4] : 88 
    

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.