Reputation: 151
#include <stdio.h>
void sort(int *ptr, int n) {
int i,j,tmp;
for (i=0;i<n;i++)
for (j=0;j<n;j++)
if (ptr[i] < ptr[j])
{
tmp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=tmp;
}
}
int main() {
int i,n;
int *ptr;
printf("Nr. of elements : 5 \n");
n=5;
ptr=(int*)malloc( n * sizeof(int));
for (i=0;i<n;i++) {
scanf("%d",&ptr[i]);
}
printf("Initial array is : ");
for (i=0;i<n;i++) {
printf("%d ",ptr[i]);
}
sort(ptr,n);
printf("Sorted array is : ");
for (i=0;i<n;i++) {
printf("%d ",ptr[i]);
}
return 0;
}
This is my code. I'm trying to sort a pointer array using a function.
Whatever the (int) input, it sorts out fine.
My confusion is that i'm using
ptr[i] < ptr[j]
instead of
ptr[i] > ptr[j]
as it should normally be to sort it ascending.
Why is that?
Upvotes: 2
Views: 168
Reputation: 41180
No, your confusion is misplaced. Look at the for
loops, and the relation between i
and j
. There are times when i < j
and times when i > j
, so what constitutes being "out of order" and requiring a swap?
The inner loop should start at i+1
not at '0'; that will make the relation between i
and j
invariant.
Upvotes: 4
Reputation: 81926
Given your loops go from i = 0 .. n
and j = 0 .. n
, there is no guarantee in your code that i < j
.
There's two ways to fix this:
void sort(int *ptr, int n) {
int i,j,tmp;
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (i < j && ptr[i] < ptr[j]) { // Note the changed conditional
tmp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=tmp;
}
}
}
}
or
void sort(int *ptr, int n) {
int i,j,tmp;
for (i=0; i<n; i++) {
for (j=i+1; j<n; j++) { // Note the changed start value
if (ptr[i] < ptr[j]) {
tmp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=tmp;
}
}
}
}
Upvotes: 4
Reputation: 191
As we can see, you are using bubble sort. In bubble sort, our main intention is either transfer the heavier element to the end or lighter element to the top.
(ptr[i] < ptr[j])
what you are doing is moving the heavy elements to the end of the array, this is why whenever you are finding ptr[j](j is an inner loop variable) which is bigger than the ptr[i] (outer loop variable), you are doing a swap.
Upvotes: -1