我想使用指针而不是数组下标对从最小到最大的数组进行排序。我不知道问题出在哪里,但是当我运行这段代码时,这些值以与输入相同的顺序返回。 find_largest和swap函数都按照他们的说法完成。 selection_sort函数使用for循环将数字从右到左排序(从最大到最小,从右到左)。我一直盯着这一段时间,它看起来应该很好,但就像我说的,出于某种原因,这些数字以他们输入的顺序返回。 这里是我的代码:用c指针排序数组
#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;
}
相反,你的'交换()'函数值不一定做它说什么。首先,交换函数参数的值对函数外部没有影响。但更重要的是,这不是你想要交换的指针,而是它们指向的值。 –
[固定代码](http://ideone.com/GcM14V) – BLUEPIXY
在'swap'中,你实际上需要'int temp;'。然后,修复其余的代码。 – jxh