Complementary task for topic: 8
M Nemeth · 2023-08-29 15:21:04.628218'
Dynamic arrays: Sorting
Dynamic arrays: Sorting
Create a C program that sorts a dynamic integer array in ascending order using pointers and a separate function.
Hint: Define a function sortArray that takes a pointer to the dynamic array and the size of the array as arguments.
The function should sort the elements of the array in ascending order using any sorting algorithm of your choice (e.g., bubble sort, selection sort, etc.).
In the main function, ask the user to input the size of the array.
Allocate memory for the dynamic array based on the user input.
Ask the user to input the elements of the dynamic array.
Call the sortArray function, passing the dynamic array and the size.
Print the sorted elements of the dynamic array.
Solution
#include
#include
void sortArray(int* arr, int size) {
// Bubble Sort Algorithm
int temp;
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
int* dynamicArray = (int*)malloc(size * sizeof(int));
printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &dynamicArray[i]);
}
sortArray(dynamicArray, size); // Pass the address of the first element of the array
printf("\nSorted Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", dynamicArray[i]);
}
free(dynamicArray);
return 0;
}
Explanation
In this task, we define a sortArray function that takes a pointer arr to the dynamic array and the size of the array as arguments. Inside the sortArray function, we use the Bubble Sort algorithm to sort the elements of the array in ascending order. This involves swapping adjacent elements until the array is sorted. In the main function, we ask the user to input the size of the array and allocate memory for the dynamic array using malloc. We ask the user to input the elements of the dynamic array using a for loop. We call the sortArray function, passing the dynamic array and the size. Finally, we print the sorted elements of the dynamic array using printf. Don't forget to free the dynamically allocated memory using free at the end of the program to avoid memory leaks.