Skip to main content

Sort array using a function

Short answer

Read values into array in main(), pass array to sortAsc() which uses bubble sort (adjacent comparison and swap) for ascending order. Since array is passed by reference, sorted array is directly available in main() for display.

Write a program to take a list of values from user into an array. Pass the list to a function which sorts the values in ascending order. Display the sorted list from main program.

Method

The values are read into an array in main(). The array name is passed to sortAsc(), which sorts it in place with bubble sort: adjacent elements are compared and swapped if the left one is bigger, and after each pass the largest of the remaining elements moves to the end. Because arrays are passed by address, the sorted array is directly available in main(), which displays it.

#include <stdio.h>

void sortAsc(int a[], int n)
{
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - 1 - i; j++)
            if (a[j] > a[j + 1]) {
                int t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
}

int main(void)
{
    int a[100], n;
    printf("How many values? ");
    scanf("%d", &n);
    printf("Enter the values: ");
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    sortAsc(a, n);                 /* array is changed in place */
    printf("Sorted list: ");
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Sample run

Input: 6 42 7 19 3 88 25

How many values? Enter the values: Sorted list: 3 7 19 25 42 88

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →