一、将一个字符串从两边到中间依次输出
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<windows.h>
int main()
{
char arr1[] = "welcome to Mysterious superstar";
char arr2[] = "*******************************";
int left = 0;
int right = strlen(arr1)-1;
for (left = 0, right = strlen(arr1) - 1; left <= right; left++, right--)//
{
Sleep(600);//让运行速度慢下来
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf("%s", arr2);
Sleep(600);
system("cls");
}
system("pause");
return 0;
}
二、折半(二分)查找
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<windows.h>
int main()
{
//折半查找
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]) - 1;
int key = 33;
int mid = 0;
while(left <= right)
{
mid = (left + right) / 2;
if (arr[mid] < key)
{
left = left + 1;
}
else if (arr[mid] > key)
right = right - 1;
else
break;
}
if (left <= right)
printf("找到了下标是%d\n", mid);
else
printf("没找到\n");
system("pause");
return 0;
}
提高版:将判断部分做成函数去调用的方式
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include<windows.h>
//折半查找
int bin_sreach(int arr[], int left, int right, int key)
{
int mid = left+(right-left)/2;//求两个数的平均数
while (left <= right)
{
mid = (left + right) / 2;
if (arr[mid] < key)
{
left = left + 1;
}
else if (arr[mid] > key)
right = right - 1;
else
return mid;
}
return -1;
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]) - 1;
int key = 27;
printf("%d", bin_sreach( arr, left , right , key));
system("pause");
return 0;
}
应该注意的是:字符串后面会自动加上“\0”。但strlen()函数并不计算它。