Problem 58

author
By Supreme2023-03-16
Problem Statement :
Write a program for sorting using pointer.
Code:

#include <stdio.h>

void sort(int *arr, int n);

int main() {

//58. Write a program for sorting using pointer.

printf("\t\tSorting\n");
printf("======================================\n\n");


int size;
printf("Enter The Number Of Elements : ");
scanf("%d",&size);
int arr[size];
int i;

for(i=0;i<size;i++){

printf("\nEnter The Element [%d] : ",i+1);
scanf("%d",&arr[i]);
}

printf("\n\n--------------------------------------");
printf("\n\nBefore Sorting: ");

for (i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n\n");

sort(arr, size);

printf("\nAfter sorting: ");
for (i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n--------------------------------------\n\n");

return 0;
}

void sort(int *arr, int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (*(arr + j) > *(arr + j + 1)) {
temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}
}

Description :
  • This program sorts an array of integers using a pointer.
  • The program first declares a function named sort, which takes two arguments - an integer pointer and an integer representing the size of the array. This function will be used for sorting the array.
  • In the main function, the program asks the user to enter the number of elements in the array and then reads those elements using a loop.
  • The program then prints the array before sorting it, and passes the array and its size to the sort function.
  • The sort function implements the bubble sort algorithm using pointer arithmetic. The outer loop iterates through all the elements in the array except the last one, and the inner loop compares adjacent elements and swaps them if they are in the wrong order.
  • After the array is sorted, the program prints it again to show the sorted order.
  • Overall, this program demonstrates how to use pointers to implement a sorting algorithm in C.
Output Image:
Output-image

© Copyright 2022. All right reserved, GTU Coder.