练习:
冒泡,插排,选排
实现字符串拼接,复制,求长
#include <stdio.h>
#include <malloc.h>
#define MAX 100
void insertion_sort() {
int a[] = {6, 4, 5, 3, 2, 1};
int length = sizeof(a) / sizeof(int);
for (int i = 1; i < length; ++i) {
for (int j = 0; j < i; ++j) {
if (a[i] < a[j]) {
int temp = a[i];
for (int k = j; k <= i; ++k) {
a[i] = a[k];
a[k] = temp;
temp = a[i];
}
}
}
}
for (int i = 0; i < length; ++i) {
printf("%d", a[i]);
}
}
void bubble_sort() {
int a[] = {6, 4, 5, 3, 2, 1};
int length = sizeof(a) / sizeof(int);
for (int i = 0; i < length; ++i) {
for (int j = 0; j < length; ++j) {
int temp;
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < length; ++i) {
printf("%d", a[i]);
}
}
void select_sort() {
int a[] = {6, 4, 5, 3, 2, 1};
int length = sizeof(a) / sizeof(int);
for (int i = 0; i < length; ++i) {
for (int j = i + 1; j < length; ++j) {
int temp;
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < length; ++i) {
printf("%d", a[i]);
}
}
int str_len(char *p) {
int len = 0;
for (char *i = p; *i != '\0'; ++i) {
len++;
}
return len;
}
char *str_cpy(char *source) {
char str[MAX] = {'\0'}, *s = str;
for (char *i = source; *i != '\0'; ++i, ++s) {
*s = *i;
}
s = str;
return s;
}
char *str_cat(char *source, char *target) {
char str[MAX] = {'\0'}, *s = str;
for (char *i = source; *i != '\0'; ++i, ++s) {
*s = *i;
}
for (char *j = target; *j != '\0'; ++j, ++s) {
*s = *j;
}
s = str;
return s;
}
int main(int argc, char *argv[]) {
bubble_sort();
insertion_sort();
select_sort();
char a[] = "hhhhhh";
char b[] = "wwwwww";
char *c = str_cat(a, b);
printf("%s,", c);
char *d = str_cpy(a);
printf("%s", d);
int len = str_len(a);
printf("%d", len);
return 0;
}