How to swap the positions of Min and Max in an array?

百般思念 提交于 2019-12-13 17:21:24

问题


Here in the code I found the min and max values of any given array . Now I want to swap their positions, and print them out. Like Min at position of Max and vice versa. How can I change their positions? I have done it wrong, I guess.

#include <iostream>

using namespace std;

int main()
{
    int array[8] = { 0, 0, 0, 0, 0, 0, 0, 0}; 
    int min = array[0]; 
    int max = array[0]; 
    int indexOfMin = 0; 
    int indexOfMax = 0; 
    int arrSize = sizeof(array)/sizeof(array[0]); 
    int temp = 0; 

    cout << "Enter an array: "; 

    int k;
    for(k = 0; k <= arrSize; k++){ 
        cin >> array[k];
    }

    for (int i = 0; i < arrSize; i++){ 
         if(array[i] >= max ){          
            max = array[i];            
            indexOfMax = i;            
        }
    }

    for (int i = 0; i < arrSize; i++){ 
        if(array[i] == min){           
            continue;
        }
        if(array[i] < min){
            min = array[i];
            indexOfMin = i;
        }
    }

    temp = min;
    min = max;
    max = temp;

    cout << array[k] << " " <<endl;

    return 0;
}

Input = 1, 5, 9, 1, 2, 9, 1, 3
Output = 9, 5, 9, 1, 2, 1, 1, 3


回答1:


int min = array[0];
int max = array[0];

You don't know that yet. array[0] at this point of the program is 0 ... but 0 might not be an element of the array after user input.

int indexOfMin = 0;
int indexOfMax = 0;

Indexes into and the sizes of objects in memory should be of type std::size_t (<cstddef>) because it is guaranteed that std::size_t is big enough. There is no such guarantee for int.

int arrSize = sizeof(array) / sizeof(array[0]);

Use std::size() (<iterator>) for clearer code:

auto const arrSize{ std::size(array) };
int k;
for (k = 0; k <= arrSize; k++) {
    cin >> array[k]; 
}

Valid array indexes range from 0 to < N for an array array[N]. You access the array out of bounds. Use k < arrSize as condition. k should be of type std::size_t.

for (int i = 0; i < arrSize; i++) {
  if (array[i] >= max) {
      max = array[i];
      indexOfMax = i;
  }
}

for (int i = 0; i < arrSize; i++) {
  if (array[i] == min) {
      continue;
  }
  if (array[i] < min) {
      min = array[i];
      indexOfMin = i;
  }
}

If you had defined int min = array[0]; and int max = array[0]; after user input you could start these loops with i = 1. The if (array[i] == min) { continue; } buys you nothing. In contrary it wastes time with an additional comparison. Also, both loops can be combined into one:

int min{ array[0] };
int max{ array[0] };

std::size_t indexOfMin{ 0 };
std::size_t indexOfMax{ 0 };

for (size_t i{ 1 }; i < arrSize; ++i) {
    if(array[i] < min) {
        min = array[i];
        indexOfMin = i;
    }
    else if(array[i] > max) {
        max = array[i];
        indexOfMax = i;
    }
}
temp = min;
min = max;
max = temp;

Will swap the values of the variables min and max. Also, if swapping the minimal and maximal values in the array could be done that way, why remember their position? Try

temp = array[indexOfMin];
array[indexOfMax] = array[indexOfMin];
array[indexOfMin = temp];

So at the end i just write

for (k = 0; k <= 7; k++) {
    cout << array[k] << " " << endl;
}

?

No, you write

for (std::size_t k = 0; k < arrSize; k++) {
    std::cout << array[k] << " ";
}
std::cout.put('\n');

because you (should) have declared the previous k from the input loop inside the for-loop and you make it a good habit to declare and define variables as close to where they're used as possible. Also, since you want a list in one line don't use std::endl inside the loop but print a '\n' afterwards.




回答2:


You already have the indices of where the max and min are found. You also have the max and min. To swap the max and min values in the array is trivial with that information. Use:

array[indexofMin] = max;
array[indexOfMax] = min;

Suggetions for improving your code:

1. Fix the problem of accessing the array

for(k = 0; k <= arrSize; k++){ 
    cin >> array[k];
}

is a problem since you are modifying array using an out of bounds index. Change it to use k < arrSize.

2. Fix initialization of max and min

You need to initialize max and min only after the array has been populated with user input. Move the lines

int min = array[0]; 
int max = array[0]; 

to right after the loop to read the data.

3. Use just one loop for computing the max and the min

for (int i = 0; i < arrSize; i++){ 
     if(array[i] >= max ){          
        max = array[i];            
        indexOfMax = i;            
    }

    if(array[i] < min){
        min = array[i];
        indexOfMin = i;
    }
}

4. Remove the code to swap max and min

The lines

temp = min;
min = max;
max = temp;

swap the values of max and min but they don't change the contents of the array.

5. Use a loop to print the array

Instead of

cout << array[k] << " " <<endl;

use

for (int i = 0; i < arrSize; i++){ 
   cout << array[k] << " ";
}
cout << endl;



回答3:


Well, you have this code:

int min = array[0]; 
int max = array[0]; 

yes this is common technique to point them first to the first element, but you need to use actual values, not values you used to initialize data. In your data set (all positive) you will always have min == 0 as a result, and indexOfMin always pointing to 0.

The thing is you do not actually need to keep value for min and max as indexes are enough:

for (int i = 1; i < arrSize; i++) {
    if (array[indexOfMax] < array[i]) 
       indexOfMax = i;
    if (array[indexOfMin] > array[i]) 
       indexOfMin = i;

}

and now you can swap them:

std::swap( array[indexOfMax], array[indexOfMin] );

or use temp if yo are not allowed to use standard library.



来源:https://stackoverflow.com/questions/52863194/how-to-swap-the-positions-of-min-and-max-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!