0

How to swap the maximum and last element of an array?

I want to write the program which requests natural number NN (no more than 100), further sequence from NN of various numbers, changes places of the last element and the maximum, leaving other elements without change, and deduces the received array.

Sample Input 1:

8
3 6 12 1 7 19 25 4

Sample Output 1:

3 6 12 1 7 19 4 25

This is what I tried:

#include <iostream>
using namespace std;
int main() 
{
    int i,arr[100],n;
    cin>>n;
    int imin=0;
    for (int i=0; i<n; i++){cin>>arr[i];}

    int max=0;
    for (i=1;i<n;i++) 
    {
        if (arr[i]>arr[max])
            max=i;
        int tmp=arr[max];
        arr[max]=arr[n-1];
        arr[n-1]=tmp;
        for (i=0;i<n;i++)
            cout <<arr[i]<< " ";
        cout << "\n";  
    }  
    return 0;
}

It does not change places the maximum and the last. How can I do this?

cigien
  • 57,834
  • 11
  • 73
  • 112
  • What happens if `n` is input greater than 100? – Thomas Matthews Jan 15 '21 at 18:19
  • 3
    Fixing the indentation should allow the problem should to be easier to spot. – 1201ProgramAlarm Jan 15 '21 at 18:19
  • Someone really doesn't like our answers :-) – Ted Lyngmo Jan 15 '21 at 18:32
  • 1
    @TedLyngmo Looks like someone would like to close the question, and have it roomba. – cigien Jan 15 '21 at 18:33
  • @cigien Could be. I don't understand how that makes the answers "not useful" though. – Ted Lyngmo Jan 15 '21 at 18:34
  • 1
    @TedLyngmo It doesn't make the answers not useful so much as getting in the way of a poor question getting deleted. Downvoting answers to these questions is an officially frowned upon, but unfortunately relatively common practice. – cigien Jan 15 '21 at 18:37
  • @cigien That's unfortunately true. Everyone uses their votes differently and I'd personally upvote a useful answer even if I don't like the question. I didn't find this question horrible at all but someone else obviously thinks it is. – Ted Lyngmo Jan 15 '21 at 18:47

5 Answers5

2

I recommend using a loop to find the index of the maximum value, then outside of the loop swap the values.

int index = 0;
int max_value = arr[0];
int index_of_max_value = 0;
for (index = 1; index < n; ++n)
{
    if (arr[index] > max_value)
    {
        max_value = arr[index];
        index_of_max_value = index;
    }
}
std::swap(arr[index_of_max_value], arr[n-1]);
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • 1
    Most likely because people do not like the question and feel that it doesn't deserve to be answered. – SergeyA Jan 15 '21 at 18:54
2
#include <algorithm> // max_element, iter_swap

// ...

    auto me = std::max_element(arr, arr + n); // get an iterator to the largest element
    std::iter_swap(me, arr + n - 1); // swap the value at "me" with the last element

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 3
    That is a good answer, it reminds people of some algorithms not everyone uses on a daily basis, so one can forget about them. – SergeyA Jan 15 '21 at 18:52
  • 1
    @SergeyA Thanks! I think I'll never forget `std::iter_swap` after reading [deduplicator](https://stackoverflow.com/users/3204551/deduplicator)'s late answer to a question I had previously answered: [Is there a nice way to assign std::minmax(a, b) to std::tie(a, b)?](https://stackoverflow.com/a/56775211/7582247) – Ted Lyngmo Jan 15 '21 at 18:58
1

To swap the last element of the array with the maximum element of the array, first you need to find the index of the maximum element by traversing the full array. Then swap the last index of the array with the index that you get for maximum element. Your code had some mistakes i fixed them, have a look. Also see the indentation that i did, it is a good practice and it makes the code more redable.

swap(x, y) is a builtin function to swap two variable values.

You can do this like :

#include <iostream>
using namespace std;
int main() 
{
    int n;

    cin>>n;
    
    //int arr[n]; 
    // as said in the comment it's not the standard way to declare variable length array in C++, either use fixed length or use vector in c++

    vector<int> arr(n + 1);

    for (int i = 0; i < n; i++) cin >> arr[i];

    int mx = 0, idx;

    for(int i = 0; i < n; i++){
        if(arr[i] > mx){
            mx = arr[i];
            idx = i;
        }
    }

    swap(arr[n-1], arr[idx]); // swap is a builtin function
   
    for(int i = 0; i < n; i++)
         cout << arr[i] << " ";
    cout << "\n";  
 }  
return 0;}
Sahadat Hossain
  • 3,583
  • 2
  • 12
  • 19
  • 3
    [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – Rohan Bari Jan 15 '21 at 18:45
  • 3
    @SahadatHossain the fact that it is not defined by the C++ standard makes it undefined behavior, from a strict language perspective. It *working* is one possible outcome of UB. But the fact that it compiles at all means your compiler supports it as a non-standard extension to the language, so it won't be undefined behavior if your compiler vendor documents how it works. – Remy Lebeau Jan 15 '21 at 18:52
  • 1
    This answer is incorrect, VLAs are not legal C++. If you're relying on a compiler extension to make this code compile and work, please make that *very* explicit in the answer. – cigien Jan 15 '21 at 18:55
  • I got it now, learned something new, I used it for long time but didn't know that it's not the standard way. – Sahadat Hossain Jan 15 '21 at 18:56
  • 1
    Thank you for updating the answer, it's much better now. – cigien Jan 15 '21 at 19:08
1

First, you have to find the largest element index. Then swap it with the last element. Some cases may occur that the last element is the largest element so the array doesn't change at all or there are multiple maximum elements so you have to decide what to do next which element you want to swap, the first maximum element or the other one with the last element of the array.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    int n;
    cin >> n;
    vector<int> arr(n + 1);
    for(int i = 0; i < n; i++){
        cin >> arr[i];
    }

    int maxi = 0;
    for(int i = 0; i < n; i++){
        if(arr[i] > arr[maxi])
            maxi = i;
    }
    // swap is a builtin function that interchange two elements
    swap(arr[maxi], arr[n - 1]); 
    for(int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << "\n";
    return 0;
}

Sample Input:

8
3 6 12 1 7 19 25 4
4
1 2 3 4

Sample Output:

3 6 12 1 7 19 4 25
1 2 3 4
Badhan Sen
  • 617
  • 1
  • 7
  • 18
0
#include <iostream>
using namespace std;
int main() 
    {
    int i,arr[100],n;
    cin>>n;
    int imin=0;
    for (int i=0; i<n; i++){cin>>arr[i];}

    int max=0;
    for (i=1;i<n;i++) 
    {
        if (arr[i]>arr[max])
            max=i;
    } // closed the for loop here//

    int tmp=arr[max];
    arr[max]=arr[n-1];
    arr[n-1]=tmp;
    for (i=0;i<n;i++)
         cout <<arr[i]<< " ";
     cout << "\n";  
 
     return 0;
    }

Your code is good just needed to close the for loop after the max=i statement. If you have any other issue then ask.