Ad
  • Custom User Avatar

    It is considered bad coding practices to mutate an array or object in-place instead of creating a copy of it for further usage. One thing is that the original input is changed and if you want to debug your code based on the given input, it is not possible. The other thing is it will result in Undefined behaviour (UB) especially when the test setups, assertions and invoke callers are related to the input of your function, in which modifying it will cause other programs to read the incorrect initial or intermediate value.

  • Custom User Avatar

    This comment is hidden because it contains spoiler information about the solution

  • Default User Avatar

    Your right, I hadn't seen the problem from that angle. So you mean it would be better to do something like the following one :

    for(int i : arr){
        if(i < min) min = i;
        if(i > max) max = i;
    }
    
  • Custom User Avatar

    From a theoretical standpoint, looping once for the minimum and once for the maximum is equivalent to looping once and checking for maximum and minimum at the same time (time complexity).

    While this version looks nicer, you're performing a comparison of 2 values, 2 times, for each entry in the array. Additionally, you're always rewriting the value in the local variables.

    Perhaps it's better to simplify to 2 ifs, and only write when relevant.

  • Default User Avatar
  • Default User Avatar

    Great. Thus, as you can see, you can much more simplify your algorithm :p

  • Default User Avatar

    It was a homework assignment for an algorithms class I did a while back. I translated my answer from psudocode to java.

  • Default User Avatar

    I don't understand why you need to iterate through all array elements so many times while you can just do something like that :

     public static int[] findHighLow(int[] arr){
            int largest = arr[0], smallest = arr[0];
    
            for(int i = 1; i < arr.length; i++){
                largest = Math.max(arr[i], largest);
                smallest = Math.min(arr[i], smallest);
            }
            return new int[]{smallest, largest};
        }