在一维数组中找出值最小的元素,并将其值与第一个元素的值对调
时间: 2024-05-10 17:17:12 浏览: 6
可以通过遍历数组,找出最小值的索引,然后将最小值与第一个元素交换来实现。
以下是一个示例代码:
```python
def swap_min(array):
# 找出最小值的索引
min_index = 0
for i in range(len(array)):
if array[i] < array[min_index]:
min_index = i
# 将最小值与第一个元素交换
array[0], array[min_index] = array[min_index], array[0]
return array
```
例如,对于数组 `[3, 1, 4, 5, 2]`,使用 `swap_min` 函数后,会返回 `[1, 3, 4, 5, 2]`。
相关问题
用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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)