三:插入排序(原地插入排序)O(N^2)
找到位置,用此位置的值与其前面位置的值比较,直到找到合适的位置
for(i=0;i<len;i++) //要插入的数据
{
t = a[i];//非原地插入排序可不用t记录位置的值
j = i;
while(j>0 && a[j-1] > t)//寻找合适的插入位置
{
a[j] = a[j-1];
j--;
}
a[j] = t;
}
四:二分查找
int n;
scanf("%d",&n);
int begin = a[0];
int end = a[len-1];
while(begin <= end)
{
int mid = (begin + end)/2;
if(a[mid] > n)
{
end = mid - 1;
}else if(a[mid] < n)
{
begin = mid + 1;
}else
{
break;
}
}
int mid = (begin + end)/2;
if(begin <= end)
{
printf("found,located in a[%d]\n",mid);
}else
{
printf("not found\n");
}
八:字符型的一维数组
一:
主要用途:存放字符串数据 结束标志 // ‘\0’
字符串都是按照字符数组的方式存储 //“hello”---->0 1 2 3 4 5,占六个内存空间,剩下部分补零
char s[10] = "hello";
int i = 0;
while(s[i] != 0)
{
printf("%c",s[i]);
++i;
}
putchar('\n');
二:数组大小识别
字符串中 ‘\0’ 也是占空间
char s1[] = {'h','e','l','l','o'};
char s2[10] = "hello";
char s3[] = "hello";
printf("sizeof(s1) = %ld\n",sizeof(s1));
printf("sizeof(s2) = %ld\n",sizeof(s2));
printf("sizeof(s3) = %ld\n",sizeof(s3));
结果:
sizeof(s1) = 5
sizeof(s2) = 10
sizeof(s3) = 6
三:字符串操作函数gets/puts
scanf("%s",s);
gets/puts
char *gets(char *s);
参数:s代表存放字符串的一块空间的地址 返回值:s
char s[20] ={1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
gets(s);//可能导致缓冲区溢出,使栈
int i = 0;
while(s[i] !='\0')
{
printf("%c",s[i]);
++i;
}
putchar('\n');
int puts(const char *s);
参数:s 要输出的字符 返回值:成功返回非负 失败返回-1
输出自带换行
gets(s);
puts(s);
四:strlen //计算字符串长度
字符串长度:‘\0’ 前面字符的个数(不包括\0)
char s[20];
scanf("%s",s);
int i = 0;
int count = 0;
while(s[i] != '\0')
{
count++;
i++;
}
printf("long = %d\n",count);
size_t strlen(const char *s);
//参数:s要统计的字符串 返回值:返回字符串的长度值
#include<stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
char s[20];
gets(s);
printf("long = %ld\n",strlen(s));
return 0;
}
五:strcpy
字符串复制
char s1[] = "hello";
char s2[20];
int i = 0;
while(s1[i] != '\0')
{
s2[i] = s1[i];
i++;
}
s2[i] = '\0';//保证复制后的字符串有效
puts(s1);
puts(s2);
char *strcpy(char *dest, const char *src);
//参数 @src
要复制的字符 @dest
要复制到的目标 返回值:成功返回dest
失败返回NULL
#include<stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
char s1[] = "hello";
char s2[20];
strcpy(s2,s1);
puts(s1);
puts(s2);
return 0;
}