在一维数组中找出值最小的元素,并将其值与第一个元素的值对调
时间: 2024-05-16 17:13:32 浏览: 14
可以按照以下步骤实现:
1. 假设数组的名称为 arr,将第一个元素作为当前最小值,即 min_idx = 0。
2. 从第二个元素开始遍历数组,如果找到比当前最小值还小的元素,则将 min_idx 更新为该元素的下标。
3. 遍历完整个数组后,将第一个元素的值与最小元素的值进行交换。
下面是一个示例代码实现:
```python
def swap_min(arr):
min_idx = 0
for i in range(1, len(arr)):
if arr[i] < arr[min_idx]:
min_idx = i
arr[0], arr[min_idx] = arr[min_idx], arr[0]
return arr
```
可以调用该函数对数组进行测试:
```python
arr = [3, 5, 2, 8, 1]
print(swap_min(arr)) # 输出 [1, 5, 2, 8, 3]
```
相关问题
用c语言编写在一维数组中找出值最小的元素,并将其值与第一个元素的值对调
下面是用C语言编写的代码实现:
```c
#include <stdio.h>
int main() {
int arr[10] = {5, 8, 2, 9, 1, 7, 4, 6, 3, 0};
int min_index = 0;
// 找出最小元素的下标
for (int i = 1; i < 10; i++) {
if (arr[i] < arr[min_index]) {
min_index = i;
}
}
// 将最小元素与第一个元素对调
int temp = arr[0];
arr[0] = arr[min_index];
arr[min_index] = temp;
// 输出结果
printf("数组排序前:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
运行结果:
```
数组排序前:
0 8 2 9 1 7 4 6 3 5
```
以上代码先利用循环找到一维数组中最小元素的下标,再利用一个临时变量将最小元素与第一个元素对调。最后输出对调后的数组。
用c语言代码实现在一维数组中找出值最小的元素,并将其值与第一个元素的值对调
以下是实现方法:
```c
#include <stdio.h>
#define SIZE 10
int main() {
int arr[SIZE] = {5, 2, 7, 3, 9, 1, 6, 4, 8, 0};
int minIndex = 0;
// 找出最小值的下标
for (int i = 1; i < SIZE; i++) {
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
// 交换第一个元素和最小值元素的值
int temp = arr[0];
arr[0] = arr[minIndex];
arr[minIndex] = temp;
// 输出交换后的数组
for (int i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果为:
```
0 2 7 3 9 1 6 4 8 5
```
可以看到,最小值元素已经被交换到了数组的第一个位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)