交换数组/向量中所有最小和最大的数



我试图制作一个程序,交换数组或向量中所有最大和最小的数字。我想出了一个程序,但由于某种原因,我无法调试它来解决问题。它没有打印矢量,我也不知道问题出在哪里。有人能帮我吗?

所需输入和输出

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int n;
cin>>n; //size input
vector<int> arr;
for(int i=0;i<n;i++) //filling up the vector
{
int input;
cin>>input;
arr.push_back(input);
}
vector<int> arr1=arr; //copying the vector
sort(arr1.begin(), arr1.end()); //sorting the new vector
int i=0,j=n-1,i1=0,j1=n-1; //i and j are for the vector arr & i1 and j1 are for vector arr1
while(i1<j1)
{
if(arr1[i1]==arr[i] && arr1[j1]==arr[j]) //if the first and last number of the sorted vector is found in arr the swap
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i1++;
j1--;
i=0; // i and j are set to initial value so that it is checked from the start
j=n-1;;
}
else if(arr1[i1]<arr[i] && arr1[j1]==arr[j]) //if only the biggest place element is found the increase i 
{
i++;
}
else if(arr1[i1]==arr[i] && arr1[j1]>arr[j]) //if only the smallest place element is found the decrease j
{
j--;
}
else if(arr1[i1]!=arr[i] && arr1[j1]!=arr[j]) //if none of them are found then increase i and decrease j
{
i++;
j--;
}
}
for(int f=0;f<n;f++) //print the vector
cout<<arr[f]<<" ";
return 0;
}
/*
Sample input 1
6
12 34 87 56 38 98
Sample output 1
98 87 34 38 56 12
Sample input 2
6
8 7 9 2 4 6
Sample output 2
4 6 2 9 8 7
*/ 

如果能提供一些帮助,我们将不胜感激。

一个更简单的方法是制作一个索引向量,而不是对向量进行排序并尝试在原始向量中查找值。例如:

#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int n;
std::cin >> n;
std::vector<int> arr;
std::vector<int> indexes;
for (int i = 0; i < n; i++)
{
int input;
std::cin >> input;
arr.push_back(input);
indexes.push_back(i);
}
std::sort(indexes.begin(), indexes.end(), [&](int a, int b) {return arr[a] < arr[b]; });
for (int i = 0, j = n - 1; i < n / 2; i++, j--)
{
std::swap(arr[indexes[i]], arr[indexes[j]]);
}
for (int f = 0; f < n; f++)
{
std::cout << arr[f] << " ";
}
return 0;
}

最新更新