冒泡:数字排序和字符串排序

it2024-06-18  44

#include<stdio.h> #include<stdlib.h>//种随机数的函数 #include<time.h>//使随机数随时间改变,如果没有这个头文件,随机数是假随机数 void main() { int temp; int flag=0; srand((unsigned int)time(NULL));//种随机数 int a[10]; for(int m=0;m<10;++m) { a[m]=(rand()%50);//确定随机数的范围,for循环给数组赋值 printf("%d ",a[m]);//打印原有顺序的数组 } for(int i=0;i<10;++i) { for(int j=0;j<len-1;++j)//优化,因为每一次循环最大的数字都会在最后面 { if(a[j]<a[j-1]) { temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; flag=1; } } if(flag==0) { break; } } for(int n=0;n<10;++n) { printf("%d ",a[n]);//打印出排序好的数组 } } int flag;的用出处在于检查冒泡排序是否已经排序好,如果排序完成就break for循环,避免cpu空转,提高效率 另外一个优化在于要使用++i而不是i++ ```c //字符串的排序 #include<stdio.h> #include<string.h> void main() { char *str[]={"hello","world","zhou","lin","aaa"}; //一个指针数组,数组元素是存放char类型数据地址的指针 char *temp=NULL;//定义一个存放char类型数据地址的指针,但是在堆中未分配地址 for(int i=0;i<5;++i) { for(int j=0;j<5-i;++j) { if(strcmp(str[j],str[j+1])>0)//stecmp是比较字符串大小的函数 { temp=str[j];//这里是地址的赋予,即使temp没有分配地址空间也不会出现段错误 str[j]=str[j+1]; str[j+1]=temp; } //strcmp函数的返回值是int 参数值是两个str类型的数据,如果第一个大于第二个,那么返回值为1,相等返回0,否则返回-1; } } for(int i=0;i<5;++i) printf("%-8s",str[i]);//%s是字符串的输出格式-8的意思是占8个位置,左对齐 }
最新回复(0)