C编程: how to implement an insertion sort?

标签 c arrays for-loop while-loop insertion-sort

假设我有一个数字列表:

89 12 18 4 6

我想实现一个插入排序并将排序的每一步都打印到屏幕上:

Sort 1. 12 89 18 4 6
Sort 2. 4 12 89 18 6
Sort 3. 4 6 12 89 18
Sort 4. 4 6 12 18 89

这是我到目前为止的代码,我对在循环中的何处插入 printf 感到困惑。

void insertion_sort(FILE *fp, int ar[15])
{
  int i, j, temp;

  for (i = 0; i < 15; i++)
    printf("%d\n", ar[i]);

  for(i = 0; i < 15; i++) {
    temp = ar[i];
    for(j = i - 1; j >= 0 && ar[j] > temp; j--)
        ar[j + 1] = ar[j];
    ar[j + 1] = temp;
}       

最佳答案

您的排序方案实际上是选择排序:

  Sort 1. 12 89 18 4 6 
  Sort 2. 4 12 89 18 6
  Sort 3. 4 6 12 89 18
  Sort 4. 4 6 12 18 89

它找到最小的数字并将其放在列表的开头。 正常的插入排序会执行以下操作:

  Sort 1. 12 89 18 4 6
  Sort 2. 12 18 89 4 6
  Sort 3. 4 12 18 89 6
  Sort 4. 4 6 12 18 89

这就是它发现 18 小于 89 但大于 12 并在 12 和 89 之间插入 18 并且完成第一次迭代。然后重复这个过程。

这是我的代码:

void insertion(int *x,int n){ // int *x - array, n- array's length
    int i,j,k,temp,elem; // i,j,k - counters, elem - to store the element at pos x[i]
    for(i=0;i<n;i++){
        elem=x[i]; // store the element
        j=i; 
        while(j>0 && x[j-1]>elem){ // the magic(actual sorting)
            x[j]=x[j-1];
            j--;
        }
        x[j]=elem;  // swap the elements
        if(i>=1){   // here begins printing every sorting step, i>=1 because first time j is not greater than 0 so it just run through the loop first time
        printf("sort %d. ",i); // printing the step
        for(k=0;k<n;k++)    // loop through array 
            printf("%d ",x[k]); // display the elements already sorted
        printf("\n"); // when the array is displayed, insert a \n so that the next display will be on a new line
        }
    }
}

关于C编程: how to implement an insertion sort?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14807963/

相关文章:

javascript - "for"内部 "setInterval"的索引

c - 如何打印数组?

c - 如何使用 SWIG 创建带有可选参数的 TCL 函数?

c - 如何使用 C 更改 .dll 的文件版本和产品名称?

c - 搜索两个字符串中最长的子串

具有自定义类的 BufferedReader 的 java.lang.StackOverflowError

ruby-on-rails - 如何将数组的元素添加到另一个数组并删除重复项

c++ - 如何在 C++ 中的 do-while 循环结束时清除数组?

Python:循环到两个列表中较短的一个

c - 这两个计算三角形数的程序有什么区别?