derek - 2 months ago 23

C Question

I am trying to sort an array from least to greatest using pointers instead of array subscripts. I am not sure where the problem is but when i run this code, the values are returned in the same order that they were entered. The find_largest and swap functions both do exactly what they say. The selection_sort function uses a for loop to sort the numbers from right to left (greatest to smallest, right to left). I have been staring at this for a while now and it looks like it should work fine but like i said, for some reason the numbers are returned in the same order they were entered.

Here is my code:

`#include <stdio.h>`

#define N 5

void selection_sort(int *a, int n);

int *find_largest(int *a, int n);

void swap(int *p, int *q);

int main(void)

{

int i;

int a[N];

printf("Enter %d numbers to be sorted: ", N);

for (i = 0; i < N; i++)

scanf("%d", (a+i));

selection_sort(a, N);

printf("In sorted order:");

for (i = 0; i < N; i++)

printf(" %d", *(a+i));

printf("\n");

return 0;

}

void selection_sort(int *a, int n)

{

int i = 0;

int *largest;

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

largest = find_largest(a, n-i);

swap(largest, a+(n-1-i));

}

}

int *find_largest(int *a, int n){

int *p = a;

int *largest = p;

for(p = a; p < a+n-1; p++){

if(*(p+1) > *p){

largest = (p + 1);

}

}

return largest;

}

void swap(int *p, int *q){

int *temp;

temp = p;

p = q;

q = temp;

}

Answer

There are two mistakes in your code. One, logical in the find_largest function:

```
int *find_largest(int *a, int n){
int *p = a;
int *largest = p;
for(p = a; p < a+n-1; p++){
if(*(p+1) > *largest){ <---- //here you were checking for *(p)
largest = (p + 1);
}
}
return largest;
}
```

the other is with pointers in swap function:

```
void swap(int *p, int *q){
int temp;
temp = *p;
*p = *q;
*q = temp;
}
```

Source (Stackoverflow)

Comments