【发布时间】:2020-11-12 09:26:02
【问题描述】:
我正在尝试编写一个程序来交换数组或向量中的所有最大和最小数字。我想出了一个程序,但由于某种原因我无法调试它来解决问题。它没有打印矢量,我也不知道问题是什么。谁能帮帮我。
#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
*/
我们将不胜感激。
【问题讨论】:
-
如果
arr1包含arr中项目的索引可能会简单得多 -
对问题的描述完全不清楚。 “交换所有最小和最大的数字”是什么意思?
-
将输入和所需输出包含为 text,而不是链接图像(也不是代码底部的内容)。 -1.
-
在打印出数组后,尝试在末尾输出换行符。
-
您的程序似乎完全按照您希望的方式运行