一·一维数组基本算法
1·选择排序(默认排序)
int a[] = {1,-2,3,-4,5,-6,7,-8,9,0};
int len = sizeof(a) / sizeof(a[0]);
int i, j;
for(i = 0;i < len - 1;++i)
{
for(j = i + 1;j < len;++j)
{
if(a[i] > a[j])
{
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for(i = 0;i < len;++i)
{
printf("%d\n", a[i]);
}
2、冒泡排序
冒牌排序:数组相邻两比较,小的在前,大的在后
int a[] = {1,-2,3,-4,5,-6,7,-8,9,0};
int len = sizeof(a) / sizeof(a[0]);
int i, j;
for(j = len - 1;j > 0;--j)
{
for(i = 0;i < j;++i)
{
if(a[i] > a[i + 1])
{
int t;
t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}
for(i = 0;i < len;++i)
{
printf("%d\n", a[i]);
}
3.排序
int a[] = {1,3,2,4,5,7,8,9,6};
int len = sizeof(a) / sizeof(a[0]);
int i,j;
for(i = 0; i < len - 1; i++)
{
for(j = 0; j < len - i;j++)
{
if(a[i] > a[i+1])
{
int t;
t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}
4.插入法排序
int a[] = {1,-2,3,-4,5,-6,7,-8,9,0};
int len = sizeof(a) / sizeof(a[0]);
int i, j;
for(i = 1;i < len;++i)
{
int t = a[i];
j = i;
while(j > 0 && a[j - 1] > t)
{
a[j] = a[j - 1];
--j;
}
a[j] = t;
}
5.二分法查找
int a[] = {1,-2,3,-4,5,-6,7,-8,9,0};
int len = sizeof(a) / sizeof(a[0]);
int n = 9;
int begin = 0, end = len - 1, mid;
while(begin <= end)
{
mid = (begin + end) / 2;
if(a[mid] > n)
{
end = mid - 1;
}
else if(a[mid] < n)
{
begin = mid + 1;
}
else
{
break;
}
}
if(begin <= end)
{
printf("found\n");
}
else
{
printf("not found\n");
}
6.逆序
int a[] = {1,2,3,4,5,6,7,8,9,0};
int len = sizeof(a) / sizeof(a[0]);
int i;
for(i = 0;i < len / 2;++i)
{
int t;
t = a[len - i - 1];
a[len - i - 1] = a[i];
a[i] = t;
}
for(i = 0;i < len;++i)
{
printf("%d\n", a[i]);
}
二
2.1strcpy(s2,s1)
char s1[] = "Hello";
char s2[100];
int i = 0;
while(s1[i] != '\0')
{
s2[i] = s1[i];
++i;
}
s2[i] = 0;
2.2strcat(s1, s2)
char s1[100] = "Hello";
char s2[100] = "World!";
int i = 0;
while(s1[i] != '\0')
{
++i;
}
int j = 0;
while(s2[j] != '\0')
{
s1[i] = s2[j];
++i;
++j;
}
s1[i] = '\0';
2.3strcmp(s1, s2)
char s1[100] = "Hello";
char s2[100] = "He";
int i = 0;
while(s1[i] == s2[i] && s1[i] != '\0' && s2[i] != '\0')
{
++i;
}
printf("%d\n", s1[i] - s2[i]);
printf("%d\n", strcmp(s1, s2));
3.二维数组
3.1二维数组逆序
int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
int rows = sizeof(a) / sizeof(a[0]);
int cols = sizeof(a[0]) / sizeof(a[0][0]);
int i, j;
for(i = 0;i < rows;++i)
{
for(j = 0;j < cols / 2;++j)
{
int t;
t = a[i][cols - j - 1];
a[i][cols - j - 1] = a[i][j];
a[i][j] = t;
}
}
for(i = 0;i < rows;++i)
{
for(j = 0;j < cols;++j)
{
printf("%2d ", a[i][j]);
}
puts("");
}
3.2二维字符串数组选择排序
char s[][100] = {"Hello", "World!", "China!", "America"};
int rows = sizeof(s) / sizeof(s[0]);
int i, j;
for(i = 0;i < rows - 1;++i)
{
for(j = i + 1;j < rows;++j)
{
if(strcmp(s[i], s[j]) > 0)
{
char t[100];
strcpy(t, s[i]);
strcpy(s[i], s[j]);
strcpy(s[j], t);
}
}
}
for(i = 0;i < rows;++i)
{
puts(s[i]);
}