加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C编程:如何实现插入排序?

发布时间:2020-12-16 07:03:23 所属栏目:百科 来源:网络整理
导读:说我有一个数字列表: 89 12 18 4 6 我想实现一个插入排序,让它打印到屏幕上的每一步: Sort 1. 12 89 18 4 6Sort 2. 4 12 89 18 6Sort 3. 4 6 12 89 18Sort 4. 4 6 12 18 89 这是我到目前为止的代码,我对在循环中插入printf的位置感到困惑. void insertion_
说我有一个数字列表:

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("%dn",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,k,temp,elem; // i,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
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读