置换选择排序c++
时间: 2023-07-02 19: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()` 函数用于对数组进行排序。在内层循环中,我们找到当前未排序部分中最小元素的索引。如果最小元素不是当前元素,我们就交换它们。最终,我们得到一个已排序的数组。