ADVERTISEMENT
ADVERTISEMENT

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.

Example:

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

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

Program:

/*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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.