ReArrange Min/Max

Xavier Carty
2 min readOct 11, 2020

--

Arrays Min and Max

I have been going over Data Structures and Algorithms in Java on Educative.io. You guys should check it out if you get the chance. I ran into this problem with arrays. I love the solution so I am going to show you how to solve this problem.

Today we are going to talk about rearranging values in array min and max form.

In this solution, we first create an empty array whose size is equal to the size of the original array

int pointerSmall = 0;     //PointerSmall => Start of arrint pointerLarge = arr.length - 1;   //PointerLarge => End of arr//Flag which will help in switching between two pointersboolean switchPointer = true;

then we start iterating over the array and store the maximum number in the start of the array and then the minimum number next to it and so on. In the end, store the result array to the original array

for (int i = 0; i < arr.length; i++) {if (switchPointer)result[i] = arr[pointerLarge--]; // copy large valueselseresult[i] = arr[pointerSmall++]; // copy small valuesswitchPointer = !switchPointer;   // switching between samll and large
}
for (int j = 0; j < arr.length; j++) {arr[j] = result[j]; // copying to original array}}

One interesting thing about this solution is the boolean value in which i believe that we can switch pointers. I think the switch pointer could be applied to many other solutions. Full code;

class CheckMaxMin {public static void maxMin(int[] arr) {//Create a result array to hold re-arranged version of given arrint[] result = new int[arr.length];int pointerSmall = 0;     //PointerSmall => Start of arrint pointerLarge = arr.length - 1;   //PointerLarge => End of arr//Flag which will help in switching between two pointersboolean switchPointer = true;for (int i = 0; i < arr.length; i++) {if (switchPointer)result[i] = arr[pointerLarge--]; // copy large valueselseresult[i] = arr[pointerSmall++]; // copy small valuesswitchPointer = !switchPointer;   // switching between samll and large}for (int j = 0; j < arr.length; j++) {arr[j] = result[j];    // copying to original array}}

--

--

Xavier Carty

Learning new things everyday and sharing them with them world. Software Engineering , Muay Thai , and Soccer are my passions.