我正在尝试使用选择排序对一些数字进行排序,但是如果我输入
数字3 1 4 2,输出为1 1 1 3,我看不到我在做什么
错误。
void selection_sort(list *l, int list_size){
node *p = l->head, *q = l->head;
for(int i = 0; i < list_size-1; i++){
int smaller = p->key;
printf("begin: %d\n", smaller);
//find the smaller number !!OK!!
for(int j = 0; j < list_size; j++){
if(p->next == NULL) break;
if(p->key < p->next->key) smaller = p->key;
p = p->next;
}
//changing values
int tmp = smaller;
smaller = q->key;
q->key = tmp;
p = (q = q->next); //positioning pointers
}
}
最佳答案
我不确定我是否真的理解您的问题,但是如果要使用C语言编写选择排序,建议您参阅wikipedia's example which is clear and commented
[编辑]
哦好的。我仍然不太了解您的问题,但也许是您始终在此处进行相同的比较,因为您没有增加p:for(j = 0; j < size; j++){
if(p->key > p->next->key){
smaller = p->next->key;
p = p->next;}
关于c - 使用带有指针的数组,如何使用选择排序对数字进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544923/