#ifndef __MY_ALGORITHMS_H_INCLUDE__
#define __MY_ALGORITHMS_H_INCLUDE__
#pragma once
#include <vector>
// 递归求数组元素的和
int sum(const std::vector<int>& datas)
{
if (datas.size() == 0) return 0;
if (datas.size() == 1) return datas[0];
else
{
std::vector<int> temp(++datas.begin(), datas.end());
return datas[0] + sum(temp);
}
}
// 选择排序(递归)
void selectSort(std::vector<int>& arr, int start = 0)
{
// 基本的判空处理
int size = (int)arr.size();
if (size == 0) return;
// 递归的基线条件
if (start == size - 1) return;
// 找到最小的元素的下标
int minIndex = start;
for (int i = start + 1; i < size; ++i)
{
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
}
// 如果找到了,就将最小值交换到数组开头,如果没有找到,就说明数组开头就是最小值
if (minIndex != start) {
std::swap(arr[start], arr[minIndex]);
}
// 然后递归排序
selectSort(arr, start + 1);
}
// 选择排序,非递归实现,两次遍历,每次找到最大,或者最小值的下标,然后与首位交换值。
// 时间复杂度为 O(n^2)
void selectSort(std::vector<int>& arr)
{
for (int i = 0; i < (int)arr.size() - 1; ++i)
{
int minIndex = i;
for (int j = i + 1; j < (int)arr.size(); ++j)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
if (minIndex != i)
std::swap(arr[i], arr[minIndex]);
}
}
#endif // __MY_ALGORITHMS_H_INCLUDE__
C++ 选择排序,递归与非递归实现
最新推荐文章于 2024-07-26 14:15:56 发布