面试题答案
一键面试以下是使用C++ 实现的代码示例:
#include <iostream>
#include <vector>
// 比较函数的通用模板
template<typename T>
using CompareFunction = bool (*)(const T&, const T&);
// 通用的冒泡排序函数
template<typename T>
void sortGeneric(std::vector<T>& arr, CompareFunction<T> compare) {
int n = arr.size();
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (compare(arr[j + 1], arr[j])) {
std::swap(arr[j], arr[j + 1]);
}
}
}
}
// 升序比较函数
template<typename T>
bool ascending(const T& a, const T& b) {
return a < b;
}
// 降序比较函数
template<typename T>
bool descending(const T& a, const T& b) {
return a > b;
}
你可以这样使用这些函数:
int main() {
std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
// 升序排序
sortGeneric(numbers, ascending<int>);
std::cout << "Ascending: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
// 降序排序
sortGeneric(numbers, descending<int>);
std::cout << "Descending: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
在上述代码中:
CompareFunction
是一个模板别名,定义了比较函数的类型。sortGeneric
是通用的排序函数,它接受一个数组和一个比较函数指针,通过该比较函数来决定排序顺序。这里使用了冒泡排序算法作为示例,实际可以替换为其他排序算法。ascending
和descending
是两个具体的比较函数模板,分别用于升序和降序比较。- 在
main
函数中,展示了如何使用sortGeneric
函数对int
类型的数组进行升序和降序排序。同样的方式也适用于其他可比较类型,只要类型支持<
和>
运算符。
如果是使用Python,可以如下实现:
# 通用的排序函数,接受一个列表和比较函数
def sort_generic(arr, compare):
return sorted(arr, key=lambda x: x, reverse=compare)
# 升序比较函数,总是返回False
def ascending(a, b):
return False
# 降序比较函数,总是返回True
def descending(a, b):
return True
使用示例:
if __name__ == "__main__":
numbers = [5, 2, 9, 1, 5, 6]
# 升序排序
ascending_result = sort_generic(numbers, ascending)
print("Ascending:", ascending_result)
# 降序排序
descending_result = sort_generic(numbers, descending)
print("Descending:", descending_result)
在Python代码中:
sort_generic
函数接受一个列表和一个比较函数,内部使用sorted
函数结合reverse
参数来实现排序。ascending
和descending
函数用于决定排序方向,在Python中直接返回布尔值来决定是否反转排序结果。- 在
if __name__ == "__main__":
代码块中展示了如何对列表进行升序和降序排序。