标签:arr int 常见 flag mid len 算法 low
//基本查找,顺序查找:从0开始依次向后查找,找到返回对应索引值,未找到返回-1
#include <stdio.h>
int Order(int arr[],int len,int flag);
int main(){
int arr[5] = {1,2,3,4,5};
int len = sizeof(arr) / sizeof(int);
int flag = 5;
int i = 0;
int num = Order(arr,len,flag);
printf("%d",num > -1 ? num : -1);
}
int Order(int arr[],int len,int flag){
int i;
for(i = 0;i < len;i++){
if(flag == arr[i]){
return i;
}
}
return -1;
}
//二分查找、折半查找:数据必须有序,能提高查找效率
//设置low,high,mid表示数组索引
#include <stdio.h>
int main(){
int arr[5] = {1,2,3,4,5};
int len = sizeof(arr) / sizeof(int);
int flag = 9;
int low = 0,high = len - 1,mid = (low + high) / 2;
while(low <= high){
if(flag > arr[mid]){
low = mid + 1;
mid = (low + high) / 2;
}
else if(flag < arr[mid]){
high = mid - 1;
mid = (low + high) / 2;
}
else{
printf("%d",mid);
break;
}
}
if(low > high){
printf("-1");
}
}
//分块查找:块内无序,块见有序
//扩展分块查找
//哈希查找
//排序
//冒泡排序:
#include <stdio.h>
void BubbleSort(int arr[],int len);
int main(){
int arr[7] = {2,3,1,2,6,4,0};
int len = sizeof(arr) / sizeof(int),i;
printf("排序前:");
for(i = 0;i < len;i++){
printf("%d ",arr[i]);
}
BubbleSort(arr,len);
printf("排序后:");
for(i = 0;i < len;i++){
printf("%d ",arr[i]);
}
}
void BubbleSort(int arr[],int len){
int i = 0,j = 0,temp = 0;
for(i = 0;i < len;i++){//比较len - 1轮
for(j = 0;j < len - 1 - i;j++){//每轮比较len - 1 - i次
if(arr[j] > arr[j + 1]){
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
//选择排序:
void SelectSort(int arr[],int len){
int i,j;
for(i = 0;i < len - 1;i++){
int temp;
for(j = i + 1;j < len;j++){
if(arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
标签:arr,
int,
常见,
flag,
mid,
len,
算法,
low
From: https://www.cnblogs.com/izxw/p/18362257