c - 使用带有指针的数组,如何使用选择排序对数字进行排序?

标签 c arrays pointers selection-sort

我正在尝试使用选择排序对一些数字进行排序,但是如果我输入
  数字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/

相关文章:

c++ - 为什么我不能用 c = new (char*)[10] 初始化 char** c,而 c = new char*[10] 可以?

C:寻址链表内部结构

python - 如何在 Python 中调试 C 编译器错误? (malloc 错误)

c - 如何在 C/C++ 中使用 pthread 而不仅仅是带有 void 参数的 void 函数?

javascript - 根据数组的深度循环数组

php - 把 Laravel Query 变成 Key Value?

C 根据带指针的字符串输入打印特定字符

c - 用 C 中的三元运算符重构

c - Kernighan/Ritchie 的第 5.10 节命令行参数/可选参数

javascript - Map.filter()没有返回预期的输出