Sorting is a fundamental operation in computer science. In C, you can sort arrays not only with indexing but also using pointers for efficient memory access. This tutorial shows how to implement a simple sorting algorithm using pointers.
Objective
- Declare and initialize an array.
- Use pointers to sort elements in ascending order.
- Demonstrate pointer arithmetic and dereferencing.
Example C Program
#include <stdio.h>
void sort(int *arr, int size) {
int i, j, temp;
for (i = 0; i < size - 1; i++) {
for (j = i + 1; j < size; j++) {
if (*(arr + i) > *(arr + j)) {
// Swap using pointers
temp = *(arr + i);
*(arr + i) = *(arr + j);
*(arr + j) = temp;
}
}
}
}
int main() {
int arr[] = {45, 12, 98, 67, 34};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Before Sorting:\n");
for (i = 0; i < n; i++) {
printf("%d ", *(arr + i));
}
sort(arr, n);
printf("\nAfter Sorting (Ascending Order):\n");
for (i = 0; i < n; i++) {
printf("%d ", *(arr + i));
}
return 0;
}
Sample Output
Before Sorting:
45 12 98 67 34
After Sorting (Ascending Order):
12 34 45 67 98
Explanation
sort()
receives the array base address using a pointer.*(arr + i)
accesses values directly via pointer arithmetic.- Values are swapped using a temporary variable.
- Sorting is done in ascending order using a basic selection sort.
Concepts Used
- Pointers and arrays
- Pointer arithmetic
- Call by reference
- Swapping values using pointers
Key Takeaways
- Pointers offer efficient access to array elements.
- Sorting with pointers improves memory handling in C.
- This approach builds a strong understanding of pointer manipulation.
🔚 Conclusion
Sorting an array using pointers is an excellent way to deepen your understanding of C pointers. It reinforces how pointers can replace indexing and provide direct memory access, which is essential in advanced C programming and system-level development.