C PROGRAMMING PROGRAM • POINTERS & DYNAMIC MEMORY
Sort a Dynamically Allocated Array
Learn how to sort a dynamically allocated array using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
5 9 2 7 1 4
Sample output
Sorted: 1 2 4 7 9
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t count;
printf("Enter array size: ");
scanf("%zu", &count);
int *values = malloc(count * sizeof *values);
if (values == NULL && count != 0) return 1;
printf("Enter elements: ");
for (size_t index = 0; index < count; index++) scanf("%d", &values[index]);
for (size_t pass = 0; pass < count; pass++)
for (size_t index = 0; index + 1 < count - pass; index++)
if (values[index] > values[index + 1]) {
int temporary = values[index];
values[index] = values[index + 1];
values[index + 1] = temporary;
}
printf("Sorted: ");
for (size_t index = 0; index < count; index++) printf("%d ", values[index]);
putchar('\n');
free(values);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sorted: 1 2 4 7 9
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Allocate exactly the requested storage, sort through indexed pointer access, then free it.
- Display the computed result.
Allocate exactly the requested storage, sort through indexed pointer access, then free it.
EFFICIENCY
Time and space complexity
Time complexity
O(n²)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
