Sort an Array Using Pointer (Problem: 1.2)

Question 1.2 #: Write a program to sort an array using Pointer. You have to write a function sortarray(int n, int *p) where n is the total array size and p is a pointer variable that have array address to solve the problem. 

Input 5 number of elements in the array: 25 45 89 15 82

Expected Output: 15 25 45 82 89


Solution:


#include <stdio.h>
int main(){
    int n,*p,i;
    printf("Enter How Many Elemant: ");
    scanf("%d",&n);
    p=(int *)malloc(n*sizeof(int));
    printf("\nEnter Those Value: \n");
    for(i=0;i<n;i++){
        scanf("%d",p+i);
    }
    sort(p,n);
    printf("Expected Output: ");
    for(i=0;i<n;i++){
        printf("%d ",*(p+i));
    }
}
int sort(int *p,int n){
    int i,j,tmp;
    for(i=0;i<n;i++){
        for(j=i+1;j<n;j++){
            if(*(p+i)>*(p+j)){
                tmp = *(p+i);
                *(p+i)=*(p+j);
                *(p+j)=tmp;
            }
        }
    }
}


After run:

Enter How Many Elemant: 5

Enter Those Value:
25
45
89
15
82

Expected Output: 15 25 45 82 89

Process returned 0 (0x0)   execution time : 21.017 s
Press any key to continue.







 
Previous Post Next Post