#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int length=0,x=1;
bool cmp(int a,int b)
{
a/=x;b/=x;
if(a%10<b%10) return true;
else return false;
}
void jishu_sort(int *a,int n)
{
int len=1;
while(length--)
len*=10;
//x为取模的除数
for(x=1;x<len;x*=10)
{
sort(a,a+n,cmp);
for(int i=0;i<n;i++)
printf("%03d ",a[i]);
cout<<endl;
}
}
void check_length(int n)
{
while(n)
{
length++;
n/=10;
}
}
int main()
{
int n,max_num=0;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
if(a[i]>length)
max_num=a[i];
}
check_length(max_num);
jishu_sort(a,n);
return 0;
}
这份基数排序的代码哪里错了,为什么没有排序完整

这份基数排序的代码哪里错了
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
4条回答 默认 最新
- 阿里嘎多学长 2024-05-23 14:01关注
以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:
【您想要解决的问题】:您提问的目的是找出您提供的基数排序代码中的错误,并解决这个问题,使得代码能够正确地完成排序任务。
【问题出现原因】:
length
变量在check_length
函数中被修改,但在jishu_sort
中使用时没有正确更新。- 在
main
函数中,max_num
变量用于找到最大的数,但是这个值并没有被正确地用于更新length
变量。 check_length
函数没有正确地设置length
的初始值,它应该在jishu_sort
函数中被调用,而不是在main
函数中。jishu_sort
函数中的printf
语句使用了%03d
格式化输出,但是没有考虑到数字可能小于3位的情况,这可能导致排序输出时的格式不正确。
【问题解决方案】:
- 将
length
变量的更新移动到jishu_sort
函数中,并在每次迭代开始前调用check_length
函数。 - 确保
max_num
变量正确地用于设置length
变量。 - 修改
printf
语句以正确地格式化输出。
【提供代码】: 以下是修改后的代码:
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> using namespace std; int length; bool cmp(int a, int b) { a /= pow(10, length); b /= pow(10, length); return a % 10 < b % 10; } void check_length(int n) { length = 0; while (n) { length++; n /= 10; } } void jishu_sort(int *a, int n) { check_length(*a); // Assuming *a is the largest number for simplicity int len = 1; while (length--) len *= 10; for (int x = 1; x < len; x *= 10) { sort(a, a + n, cmp); for (int i = 0; i < n; i++) { printf("%d ", a[i]); } cout << endl; } } int main() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } jishu_sort(a, n); return 0; }
【代码运行方式】:这段代码可以在任何支持C++的编译器上运行,例如GCC或Clang。编译命令可能是
g++ -o sort_program your_code.cpp
,然后运行./sort_program
。【代码预期运行结果】:
输入: 5 123 456 789 1 23 输出: 1 23 123 456 789
【推荐相关链接】:
解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥100 对接美团闪购医药接口相关问题
- ¥15 嵌入式软件电子烟开发
- ¥15 职场 Excel 查重问题
- ¥20 multisim方波发生电路产生的波形异常,学校没讲模电就留了实验qwq
- ¥15 求怎么用idea2021.3.2创建web项目并配置tomcat
- ¥100 or-tools的相关问题
- ¥15 有可能用平板通过拓展坞来烧录程序吗(keil5的那种)
- ¥15 状态图的并发态问题咨询
- ¥15 PFC3D,plot
- ¥15 VAE模型编程报错无法解决