直接上代码,图:
#include
#include
#include
typedef struct{
int*pt;
int cur;
int len;
}intArr;
void bubblesort(intArr*ia){
int i,j,t,n=ia->cur;
for(i=n;i>2;i--)
for(j=1;j if(ia->pt[j]>ia->pt[j-1]){
t=ia->pt[j-1];
ia->pt[j-1]=ia->pt[j];
ia->pt[j]=t;
}
}
void printarray(intArr*ia){
int n=ia->cur;
while(n>0)
printf("%d\t",ia->pt[--n]);
printf("\n");
}
void insertarray(intArr*ia,int t){
if(ia->cur>=ia->len)
ia->pt=(int*)realloc(ia,ia->len+=10);
if(ia->pt)
ia->pt[ia->cur++]=t;
bubblesort(ia);
printarray(ia);
}
int main(){
intArr ia,iA;
int i;
ia=&iA;
ia->pt=(int)calloc(10,sizeof(int));
ia->cur=0,ia->len=10;
printf("输入待排序数列,以空格间隔,以0结尾\n");
scanf("%d",&i);
while(i!=0)
insertarray(ia,i),
scanf("%d",&i);
system("pause");
return 0;
}
上面是完整代码,下面截图:
最后一张是测试结果,可以看到在中间的某些排序中,最后两位总是错位,而且,在bubblesort()排序算法中,if()里面的>也让我很费解,按理应该降序,实际却是升序,求助大神解答
你的程序里排序时是按照大数存到低地址,小数存到高地址,输出时是先输出高地址,后输出低地址,所以输出的数是升序。而有错位是因为输出的格式是一个“%d\t”,未给定数值的位宽。即456占三个字符,而78是两个字符。
结果: 代码:#include <stdio.h>void main()
{
int i, j, temp;
int a[10];
for (j = 0; j < 9; j++)
{
for (i = 0; i < 9 - j; i++)
{
if (a[i] > a[i + 1])
{
......
答案就在这里:c语言冒泡排序算法
----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。
http://c.biancheng.net/cpp/html/2443.html
你是想要这种效果吗?
修改代码如下,可得到上面的效果。
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct{
int *pt;
int cur;
int len;
}intArr;
void bubblesort(intArr *ia){
int i,j,t,n=ia->cur;
for(i=n;i>1;i--)
for(j=1;j<i;j++)
if(ia->pt[j]<ia->pt[j-1]){
t=ia->pt[j-1];
ia->pt[j-1]=ia->pt[j];
ia->pt[j]=t;
}
}
void printarray(intArr *ia){
int n=ia->cur;
while(n>0)
printf("%3d\t",ia->pt[--n]);
printf("\n");
}
void insertarray(intArr *ia,int t){
if(ia->cur>=ia->len)
ia->pt=(int *)realloc(ia,ia->len+=10);
if(ia->pt)
ia->pt[ia->cur++]=t;
bubblesort(ia);
printarray(ia);
}
int main(){
intArr *ia,iA;
int i;
ia=&iA;
ia->pt=(int *)calloc(10,sizeof(int));
ia->cur=0,ia->len=10;
printf("输入待排序数列,以空格间隔,以0结尾\n");
scanf("%d",&i);
while(i!=0)
insertarray(ia,i),
scanf("%d",&i);
system("pause");
free(ia->pt);
return 0;
}
这是其中一次测试结果
可以看到26 54错位,54 64错位