C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C编程:如何实现插入排序?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个数字列表:

@H_502_11@89 12 18 4 6@H_502_12@

我想实现一个插入排序,让它打印到屏幕上的每一步:

@H_502_11@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@H_502_12@

这是我到目前为止的代码,我对在循环中插入printf的位置感到困惑.

@H_502_11@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; }@H_502_12@

@H_772_13@解决方法
你的排序方案实际上是选择排序:

@H_502_11@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@H_502_12@

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

@H_502_11@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@H_502_12@

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

这是我的代码

@H_502_11@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 } } }@H_502_12@

大佬总结

以上是大佬教程为你收集整理的C编程:如何实现插入排序?全部内容,希望文章能够帮你解决C编程:如何实现插入排序?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。