c++代码,对一个数组,里面随机含有若干个-1,与其他任意大于0的整数,实现对该数组除-1外其他数字从小到大排序,要求-1所在的位置不变
#include <iostream>
#include <vector>
#include <algorithm>
void sortArrayPreservingNegatives(std::vector<int>& arr) {
// 临时存储非-1的元素
std::vector<int> temp;
for (int elem : arr) {
if (elem != -1) {
temp.push_back(elem);
}
}
// 对临时数组进行降序排序, 打开注释,则为由大到小排序,默认为由小到大
std::sort(temp.begin(), temp.end()/* , std::greater<int>() */);
// 重新填充原数组,保持-1的位置不变
size_t tempIndex = 0;
for (size_t i = 0; i < arr.size(); ++i) {
if (arr[i] != -1) {
arr[i] = temp[tempIndex++];
}
}
}
int main() {
std::vector<int> arr = { 5, -1, 3, -1, 2, 8, -1, 1 };
std::cout << "Before sorting: ";
for (int elem : arr) {
std::cout << elem << " ";
}
std::cout << std::endl;
sortArrayPreservingNegatives(arr);
std::cout << "After sorting: ";
for (int elem : arr) {
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
输出结果:
Before sorting: 5 -1 3 -1 2 8 -1 1
After sorting: 1 -1 2 -1 3 5 -1 8