- 2068 Shrawan · 3+5 marks
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)
Related questions
- Sort array ascending in FORTRAN · Computer Programming, chapter 11 · asked 2×
- Sort employee structures by salary · Computer Programming, chapter 8 · asked 2×
- Pass student array; display passed students · Computer Programming, chapter 7
- Display records sorted by name from file · Computer Programming, chapter 10
- Pass array; transpose 3×3 matrix · Computer Programming, chapter 7
- Employee text file; sort into binary file · Computer Programming, chapter 10
- Array class template with max, min, sort · Object Oriented Programming, chapter 9
- Function template: sum and average of array · Object Oriented Programming, chapter 9
- Band pass (1500 rad/s, 300 rad/s) from 4th order ladder · Filter Design, chapter 3 · asked 4×
- Namespace with pass by reference program · Object Oriented Programming, chapter 2