用c语言写一个查找算法
时间: 2023-11-16 10:03:49 浏览: 37
以下是一个基于线性查找的简单示例代码,可以在一个整数数组中查找特定的数值:
```c
#include <stdio.h>
int search(int arr[], int n, int x) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
int main() {
int arr[] = { 2, 4, 6, 8, 10 };
int x = 8;
int n = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, n, x);
if (result == -1) {
printf("Element is not present in array\n");
}
else {
printf("Element is present at index %d\n", result);
}
return 0;
}
```
该代码通过循环遍历数组中的每个元素,并将其与查找值进行比较。如果找到了匹配,则返回该元素的索引。如果未找到匹配,则返回-1。
相关问题
用C语言写一个哈希查找算法
以下是一个简单的哈希查找算法的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100 // 哈希表的最大长度
typedef struct {
char key[20]; // 关键字
int value; // 值
} HashNode;
void initHashTable(HashNode* hashTable[]) {
for (int i = 0; i < MAX_SIZE; i++) {
hashTable[i] = NULL; // 初始化为NULL
}
}
int hash(char* key) {
int hashValue = 0;
for (int i = 0; i < strlen(key); i++) {
hashValue = (hashValue * 31 + key[i]) % MAX_SIZE; // 哈希函数
}
return hashValue;
}
void insert(HashNode* hashTable[], char* key, int value) {
int hashValue = hash(key);
HashNode* node = (HashNode*)malloc(sizeof(HashNode));
strcpy(node->key, key);
node->value = value;
hashTable[hashValue] = node; // 直接插入哈希表
}
int search(HashNode* hashTable[], char* key) {
int hashValue = hash(key);
if (hashTable[hashValue] != NULL && strcmp(hashTable[hashValue]->key, key) == 0) {
return hashTable[hashValue]->value; // 查找成功,返回对应的值
} else {
return -1; // 查找失败,返回-1
}
}
int main() {
HashNode* hashTable[MAX_SIZE];
initHashTable(hashTable);
insert(hashTable, "apple", 100);
insert(hashTable, "banana", 200);
insert(hashTable, "cherry", 300);
printf("%d\n", search(hashTable, "apple")); // 输出100
printf("%d\n", search(hashTable, "banana")); // 输出200
printf("%d\n", search(hashTable, "cherry")); // 输出300
printf("%d\n", search(hashTable, "orange")); // 输出-1
return 0;
}
```
这是一个简单的哈希查找算法,具体实现可以根据具体需求进行修改。
用C语言写一个二分法查找算法
```
#include<stdio.h>
int binary_search(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int result = binary_search(arr, 0, n - 1, target);
if (result == -1) {
printf("Element is not present in array\n");
} else {
printf("Element is present at index %d\n", result);
}
return 0;
}
```