置换选择排序代码c++
时间: 2023-07-02 16:06:43 浏览: 46
以下是使用 C++ 编写的置换选择排序代码:
```c++
#include <iostream>
using namespace std;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}
int main() {
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
在此代码中,我们首先定义了一个 `swap` 函数,用于交换两个数的值。然后我们实现了一个 `selectionSort` 函数,该函数使用循环遍历数组,并在每个循环中查找最小元素的索引。如果找到了最小元素,则将其与当前元素交换。最后,我们在主函数中调用 `selectionSort` 函数来对数组进行排序,并打印排序后的结果。