随机生成1到10000的10000个随机数,并用插入排序进行排序,再用二分查找查找其中的某一个数
时间: 2024-02-18 12:04:22 浏览: 83
随机数排序_20个随机数_数组排序_源码
5星 · 资源好评率100%
生成随机数代码如下:
```python
import random
random_list = [random.randint(1, 10000) for _ in range(10000)]
```
插入排序代码如下:
```python
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
```
二分查找代码如下:
```python
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
```
然后,我们可以将这些代码组合起来,生成随机数、排序并查找其中的一个数:
```python
import random
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
random_list = [random.randint(1, 10000) for _ in range(10000)]
insertion_sort(random_list)
target = random.choice(random_list)
idx = binary_search(random_list, target)
if idx != -1:
print(f"{target} found at index {idx}")
else:
print(f"{target} not found")
```
这段代码首先生成了10000个1到10000的随机数,并通过插入排序进行排序。然后,随机选择一个数作为查找目标,并通过二分查找查找该数在数组中的位置。最后,输出查找结果。
阅读全文