鱼C论坛

 找回密码
 立即注册
查看: 2558|回复: 1

[已解决]请问这个插入排序的代码怎么写

[复制链接]
发表于 2022-8-13 16:56:01 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
这是我写的插入排序的代码,但是这个程序无法输出正常的结果,请问是怎么回事
  1. #include<iostream>
  2. using namespace std;
  3. int a[8] = {2, 7, 1, 5, 8, 4, 6, 3}, n = 8;
  4. void sort_a() {
  5.         for(int okpart=1; okpart<n; ++okpart) {
  6.                 int i = okpart;
  7.                 int temp = a[i];
  8.                 while(i >= 1 && temp < a[i-1]) {
  9.                         a[i--] = a[i-1];
  10.                 }
  11.                 a[i] = temp;
  12.         }
  13. }
  14. int main()
  15. {
  16.         sort_a();
  17.         for(int i=0; i<n; ++i) {
  18.                 cout<<a[i]<<" ";
  19.         }
  20.         return 0;
  21. }
复制代码
最佳答案
2022-8-13 17:39:09
  1. #include<iostream>
  2. using namespace std;
  3. int a[8] = {2, 7, 1, 5, 8, 4, 6, 3}, n = 8;
  4. void sort_a() {
  5.         for(int okpart=1; okpart<n; ++okpart) {
  6.                 int i = okpart;
  7.                 int temp = a[i];
  8.                 while(i >= 1 && temp < a[i-1]) {
  9.                                 a[i]=a[i-1];
  10.                         a[i-1]=temp;
  11.                         i--;
  12.                 }
  13.         }
  14. }
  15. int main()
  16. {
  17.         sort_a();
  18.         for(int i=0; i<n; ++i) {
  19.                 cout<<a[i]<<" ";
  20.         }
  21.         return 0;
  22. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-8-13 17:39:09 | 显示全部楼层    本楼为最佳答案   
  1. #include<iostream>
  2. using namespace std;
  3. int a[8] = {2, 7, 1, 5, 8, 4, 6, 3}, n = 8;
  4. void sort_a() {
  5.         for(int okpart=1; okpart<n; ++okpart) {
  6.                 int i = okpart;
  7.                 int temp = a[i];
  8.                 while(i >= 1 && temp < a[i-1]) {
  9.                                 a[i]=a[i-1];
  10.                         a[i-1]=temp;
  11.                         i--;
  12.                 }
  13.         }
  14. }
  15. int main()
  16. {
  17.         sort_a();
  18.         for(int i=0; i<n; ++i) {
  19.                 cout<<a[i]<<" ";
  20.         }
  21.         return 0;
  22. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-24 00:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表