Given an array of size n, the task is to sort this array using pointers in C.
Examples:
Input: n = 5, arr[] = {0, 23, 14, 12, 9} Output: {0, 9, 12, 14, 23} Input: n = 3, arr[] = {7, 0, 2} Output: {0, 2, 7}
Approach: The array can be fetched with the help of pointers with the pointer variable pointing to the base address of the array. Hence in order to sort the array using pointers, we need to access the elements of the array using (pointer + index) format.
Below is the implementation of the above approach:
Program:
#include // Function to sort the numbers using pointers void sort(int n, int* ptr) { int i, j, t; // Sort the numbers using pointers for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (*(ptr + j) < *(ptr + i)) { t = *(ptr + i); *(ptr + i) = *(ptr + j); *(ptr + j) = t; } } } // print the numbers for (i = 0; i < n; i++) printf("%d ", *(ptr + i)); } // Driver code int main() { int n = 5; int arr[] = { 0, 23, 14, 12, 9 }; sort(n, arr); return 0; }
Output:
0 9 12 14 23
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.