插入排序,二分查找,字符数组 day8

三:插入排序(原地插入排序)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;
}

六:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值