利用指针将最小数与第一个数调换,最大数与最后一个数对换
时间: 2023-12-04 21:41:49 浏览: 137
以下是利用指针将最小数与第一个数调换,最大数与最后一个数对换的C++代码实现:
```c++
#include <iostream>
using namespace std;
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void swapMinMax(int arr[], int n) {
int min_idx = 0, max_idx = 0;
for (int i = 1; i < n; i++) {
if (arr[i] < arr[min_idx]) {
min_idx = i;
}
if (arr[i] > arr[max_idx]) {
max_idx = i;
}
}
swap(&arr[0], &arr[min_idx]);
swap(&arr[n-1], &arr[max_idx]);
}
int main() {
int arr[] = {3, 5, 2, 7, 6, 4, 1};
int n = sizeof(arr)/sizeof(arr[0]);
<< "Original array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
swapMinMax(arr, n);
cout << "\nArray after swapping min and max: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
阅读全文