#include <stdio.h>
void swap(int *a, int *b) //交换a和b的值
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void print_array(int *a, int len) //打印函数
{
int i;
for(i = 0; i < len; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
void bubble_sort(int *a, int len) //冒泡排序,int *a定义指针变量,是数组a中a[0]的首地址
{
int i, j;
for(i = 0; i < len - 1; i++)
{
for(j = 0; j < len - 1 - i; j++)
{
if(a[j] > a[j+1])
{
swap(a + j, a + j + 1); //调用swap函数.相当于swap(&a[j], &a[j + 1]).
}
}
}
print_array(a, len);
}
int bin_search1(int *a, int start, int end, int target) //递归法写二分法
{
int mid = (start + end) / 2;
if(end < start)
{
return -1;
}
if(a[mid] == target)
{
return mid;
}else if(a[mid] > target)
{
return bin_search1(a, start, mid - 1, target);
}else
{
return bin_search1(a, mid + 1, end, target);
}
}
int bin_search2(int *a, int start, int end, int target) //迭代法写二分法
{
int mid = (start + end) / 2;
while (end > start)
{
if(a[mid] == target)
{
return mid;
}else if(a[mid] < target)
{
start = mid;
mid = (mid + end) / 2;
}else
{
end = mid;
mid = (start + mid) / 2;
}
}
return -1;
}
int select_max(int *a, int len) //函数:找出数组中最大的在数组中的位置
{
int max = a[0];
int max_position = 0;
int i;
for(i = 1; i < len; i++)
{
if(a[i] > max)
{
max = a[i];
max_position = i;
}
}
return max_position;
}
void select_sort(int *a, int len) //把最大的往后交换(与上面的函数一起写选择排序法)
{
int i;
int max_position;
for(i = 0; i < len; i++)
{
max_position = select_max(a, len - i);
swap(a + max_position, a + len - i - 1);
}
print_array(a, len);
}
void select_sort2(int *a, int len) //两重循环写选择排序法
{
int i, j;
int max_value;
int max_position;
for(i = 0; i < len; i++)
{
max_value = a[0];
max_position = 0;
for(j = 0; j < len - i; j++)
{
if(a[j] > max_value)
{
max_value = a[j];
max_position = j;
}
}
swap(a + max_position, a + len - i - 1);
}
print_array(a, len);
}
void insert_sort1(int *a, int len)
{
int i, j;
int pos;
int value;
for (i = 1; i < len; i++)
{
value = a[i];
for (j = i - 1; j >= 0; j--) //若不满足条件,循环结束后j=-1
{
if (value >= a[j])
{
break;
}
}
pos = j;
for (j = i - 1; j > pos; j--)
{
a[j + 1] = a[j];
}
a[pos + 1] = value;
}
print_array(a, len);
}
int main()
{
int i;
int a[] = {100, 99, -1, 32, 22, 77, 201, -100};
int len = sizeof(a) / sizeof(a[0]);
int ret1, ret2;
int target;
for(i = 0; i < len; i++)
{
printf("%d ", a[i]);
}
printf("\n");
bubble_sort(a, len);
printf("target:");
scanf("%d", &target);
ret1 = bin_search1(a, 0, len - 1, target);
if(ret1 < 0)
{
printf("Can't find target!\n");
}
else
{
printf("%d %d %d\n", ret1, target, a[ret1]);
}
printf("target:");
scanf("%d", &target);
ret2 = bin_search2(a, 0, len - 1, target);
if(ret2 < 0)
{
printf("Can't find target!\n");
}
else
{
printf("%d %d %d\n", ret2, target, a[ret2]);
}
select_sort(a, len);
select_sort2(a, len);
printf("插入排序:\n");
insert_sort1(a, len);
return 0;
}