mathematica写一个,搜索最优算法
时间: 2023-10-07 08:10:57 浏览: 91
这里提供几种常见的搜索最优算法的 Mathematica 代码:
1. 线性搜索:
LinearSearch[list_, value_] := Module[{pos = 0, i},
For[i = 1, i <= Length[list], i++,
If[list[[i]] == value,
pos = i;
Break[];
];
];
pos
]
2. 二分搜索:
BinarySearch[list_, value_] := Module[{left = 1, right = Length[list], mid},
While[left <= right,
mid = Floor[(left + right)/2];
If[list[[mid]] == value,
Return[mid],
If[list[[mid]] < value,
left = mid + 1,
right = mid - 1
]
]
];
-1
]
3. 插值搜索:
InterpolationSearch[list_, value_] := Module[{left = 1, right = Length[list], pos},
While[left <= right && list[[left]] <= value && list[[right]] >= value,
pos = left + Floor[(value - list[[left]])*((right - left + 1)/(list[[right]] - list[[left]]))];
If[list[[pos]] == value,
Return[pos],
If[list[[pos]] < value,
left = pos + 1,
right = pos - 1
]
]
];
-1
]
4. 哈希搜索:
HashSearch[list_, value_] := Module[{table = Association[], i},
Do[table[list[[i]]] = i, {i, 1, Length[list]}];
table[value]
]
阅读全文