Reputation: 1336
I written a sorting to an ascending order program using pointers in C.Logically this program works an ascending order,but output is descending order.What happened to this program.
This is my code :
#include<stdio.h>
#include<stdlib.h>
main()
{
int n,i,j,t,*ptr,sum=0;
printf("Enter number of elements to sort : ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));
if(ptr==NULL)
{ printf("Error occurred memory not allocated \n"); exit(0); }
printf("Enter the elements of Array \n");
for(i=0;i<n;i++)
{
scanf("%d",ptr+i);
}
for(i=0;i<n;i++){
for(j=0;j<n;j++)
{
if( *(ptr+i) > *(ptr+j))
{
t = *(ptr+i);
*(ptr+i) = *(ptr+j);
*(ptr+j) = t;
}
}
}
for(i=0;i<n;i++)
{
printf("\n%d\n",*(ptr+i));
}
free(ptr);
}
Upvotes: 0
Views: 10040
Reputation: 11
your program is correct but the line:
if( *(ptr+i) > *(ptr+j))
makes the arrangement in descending order, just make that line:
if( *(ptr+i) < *(ptr+j))
and the output will be in ascending order.
Upvotes: 1
Reputation: 1927
OK let's do it step by step by a testcase that reproduces the "error".
Suppose that the size of the array is 5, and the user input is 5, 3, 4, 2, 0 , so we have after iniliazization:
a[0]=5;
a[1]=3;
a[2]=4;
a[3]=2;
a[4]=0;
1) i = 0 ,j = 0 : (5 is not > 5) so no change
2) i = 0, j = 1 : (5 is > than 3) so a[0] -> 3 , a[1] -> 5
3) i = 0, j = 2 : (3 is not > 4) so no change
4) i = 0, j = 3 : (3 is > than 2) so a[0] -> 2 , a[3] -> 3
5) i = 0, j = 4 : (2 is > than 0) so a[0] -> 0 , a[4] -> 2
Now i=1;
1) i = 1, j = 0 : (5 is > than 0) so a[1] -> 0 , a[0] -> 5
You see, that you write a[0] = 5 again. This is the main error of your algorithm. If bubbleshort is what you want to implement have a better look at the algorithm (and after that check some more effective sorting algorithms like quicksort.
Upvotes: 1
Reputation: 1339
I think you are trying to implement Bubble Sort. There is a logical problem in the code in second for loop
for(j=0;j<n;j++)
Change it to
for(j=1;j<n-1;j++).
I think this will fix the issue
Upvotes: 0
Reputation: 8247
Two things
1) For ascending order, change the if statement to
if( *(ptr+i) < *(ptr+j) )
2) You don't need to check the entire array every time. You can start from the position of the previous lowest value.
for(i=0; i<(n-1); i++){
for(j=i+1; j<n; j++) {
...
}
}
Upvotes: 2