C语言程序设计--数组.pptVIP

  • 1
  • 0
  • 约1.88万字
  • 约 65页
  • 2019-11-06 发布于广东
  • 举报
* 华中科技大学计算机学院 * 例8.29 二分查找函数 void main(void) { int x[]={1,3,5,7,9,11,13,15,17,19},index; index=BinarySearch(x,11,10); if(index!=-1) printf(find %d!\n,x[index]); else printf(not find!\n); } 程序的运行结果是: find 11! * 华中科技大学计算机学院 * 8.6.3 选择法排序 12 2 -21 5 67 89 -12 34 假设有下面的8个整数构成的数组 算法思想 首先找出数组内8个元素中最小的元素 然后将它与第一个元素(下标为0)交换 再在剩余的后续7个元素中找出最小的元素,再将它与第二个元素(下标为1)交换 余以类推,直到在最后剩余的两个元素中找出较小者并将较大者放在最后(下标为7)为止 * 华中科技大学计算机学院 * 例8.30 用选择法进行排序 #include stdio.h int f_small(int a[], int begin, int end) /*在begin与end之间找最小数*/ { int i, p=begin; for(i=begin; i=end; i++) if(a[i]a[p]) p=i; return p;} void sel_sort(int a[], int n) { /*排序函数*/ int cur, index, t; for(cur=0;curn-1;cur++) { index=f_small(a,cur,n-1); if(index!=cur) t=a[cur], a[cur]=a[in dex], a[index]=t;} } void main(void) { int x[]={12,2,-21,5,67,89, -12,34}, i, n; n=8; sel_sort(x,n); for(i=0; i8; i++) printf(%d , x[i]); printf(\n); } * 华中科技大学计算机学院 * 8.3.2 字符数组的初始化 通过初始化列表 char s1[8]={ˊWˊ,ˊuˊ,ˊhˊ,ˊaˊ,ˊnˊ,ˊ\0ˊ}; ˊ\0ˊ必须在初始化列表中显示给出 用字符串初值 char s2[28]=〞Computer Science〞; 末尾将自动加上一个ˊ\0ˊ 第三种方法 数组长度未明显给出 char s3[]=〞Computer Engineering〞; 字符数组的容量恰好等于字符串的存储长度 * 华中科技大学计算机学院 * 8.4 字符串处理函数 串操作函数 求字符串长度 字符串的拷贝 字符串的比较 字符串的连接 求字符串的子串 删除字符串首尾空白字符 从字符串中删除所有与给定字符相同的字符 将字符串反转等函数 * 华中科技大学计算机学院 * 例8.14 求字符串长度的函数 int strlen(char s[]) { int j=0; while(s[j]!= ′\0′) j++; return j; } void main(void) { char str[]=there is a boat on the lake; int length; length = strlen(str); printf(length of the string is %d\n,length); } 运行结果: length of the string is 28 * 华中科技大学计算机学院 * 例8.15 字符串拷贝的函数 void strcpy(char t[], char s[]) { int j=0; while(t[j]=s[j++]) ; } void main(void) { char str1[30], str2[]= there is a boat on the lake.; strcpy(str1,str2); puts(str1); } 运行结果: there is a boat on the lake. * 华中科技大学计算机学院 * 例8.16 两个字符串比较函数 比较规则 从两个字符串的第一个字符起开始 按照字符ASCII码值的大小进行比较 返回规定 当两个字符串相等时,返回0 当第一个串大于第二个串时,返回一个大于零的值 当第一个串小于第二个串时,返回一

文档评论(0)

1亿VIP精品文档

相关文档