Write a C program to sort numbers in ascending order using functions.
#include <stdlib.h>
/* sorts the data in ascending order */
void ascendingOrder(int data[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
temp = data[i];
for (j = i + 1; j < n; j++) {
/* swapping big and small */
if (temp > data[j]) {
temp = data[j];
data[j] = data[i];
data[i] = temp;
}
}
}
return;
}
int main() {
int n, *data, i;
/* get the number of inputs from the user */
printf("Enter the number of inputs:");
scanf("%d", &n);
/* allocate memory to hold n elements */
data = (int *) malloc(sizeof(int) * n);
/* get n inputs from the user */
for (i = 0; i < n; i++) {
printf("data[%d]:", i);
scanf("%d", &data[i]);
}
/* sort the data in ascending order */
ascendingOrder(data, n);
/* print the results after sorting */
printf("\nAfter sorting:\n");
for (i = 0; i < n; i++) {
printf("%d ", data[i]);
}
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of inputs:5
data[0]:19
data[1]:17
data[2]:29
data[3]:57
data[4]:11
After sorting:
11 17 19 29 57
Enter the number of inputs:5
data[0]:19
data[1]:17
data[2]:29
data[3]:57
data[4]:11
After sorting:
11 17 19 29 57
No comments:
Post a Comment