写一个c++代码选择排序
以下是一个简单的C++选择排序代码:
#include <iostream>
using namespace std;
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;
}
}
// swap the minimum value with the current position
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
int main()
{
int arr[] = { 5, 2, 8, 1, 9 };
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;
}
该程序首先定义了一个名为selectionSort的函数,该函数使用选择排序算法对传入的整数数组进行排序。然后,程序在main函数中定义了一个整数数组arr,并计算出数组的大小。接下来,程序调用selectionSort函数对数组进行排序。最后,程序输出已排序的数组
原文地址: http://www.cveoy.top/t/topic/dcRk 著作权归作者所有。请勿转载和采集!