今天练习了几个小代码
#include<stdio.h>
void order(int arr[], int len);
int main()
{
int arr[] = { 3,5,2,1,4 };
int len = sizeof(arr) / sizeof(int);
order(arr, len);
for (int i = 0; i < len; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
void order(int arr[], int len)
{
for (int i = 0; i < len - 1; i++)
{
for (int j = 1; j < len - i; j++)
{
if (arr[j] < arr[j - 1])
{
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
#include<stdio.h>
int binsearch(int arr[], int len, int num);
int main()
{
int arr[] = { 7,23,79,81,103,127,131,147 };
int len = sizeof(arr) / sizeof(int);
int num = 131;
int index = binsearch(arr, len, num);
printf("%d\n", index);
return 0;
}
int binsearch(int arr[], int len, int num)
{
int max = len - 1;
int min = 0;
//mid得写在循环里面
while (min <= max)
{
int mid = (min + max) / 2;
if (num > arr[mid])
{
min = mid + 1;
}
else if (num < arr[mid])
{
max = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
#include<stdio.h>
int order(int arr[], int len, int num);
int main()
{
int arr[] = { 11,22,55,77,44 };
int len = sizeof(arr) / sizeof(int);
int num = 55;
int index = order(arr, len, num);
printf("%d\n", index);
return 0;
}
int order(int arr[], int len, int num)
{
//从头到尾全部检查过一遍后,如果没有,才能返回-1
for (int i = 0; i < len; i++)
{
if (arr[i] == num)
{
return i;
}
}
//else不能写在里面,和昨天写的代码类似
return -1;
}
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void printArr(int arr[], int len);
int main()
{
int arr[] = { 1,2,3,4,5 };
int len = sizeof(arr) / sizeof(int);
printArr(arr, len);
for (int i = 0; i < len; i++)
{
srand(time(NULL));
int index = rand()%5;
int temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
printArr(arr,len);
return 0;
}
void printArr(int arr[], int len)
{
for (int i = 0; i < 5; i++)
{
printf("%d\n", arr[i]);
}
}