Home > Blockchain >  Removing a redundant variable/shortening code
Removing a redundant variable/shortening code

Time:06-21

I need to remove the "min" variable and still allow the sorting program to run however, I am confused on where exactly to start.

    int[] A = {13, 5, 2, 0, 3, 1, 21, 1, 8};


    for (int k=0; k<A.length-1; k  ) {

        int min = A[k];
        int minPosition = k;

        for (int i=k 1; i<A.length; i  ) {
            if (A[i] < min) {
                min = A[i];
                minPosition = i;
            }
        }
        int temp = A[k];
        A[k] = A[minPosition];
        A[minPosition] = temp;
    }

    for (int i=0; i<A.length; i  ) {
        System.out.println (A[i]);
    }

CodePudding user response:

You have both min and minPosition:

int min = A[k];
int minPosition = k;

Start by removing the declaration for min altogether (delete the line int min = A[k]), delete the line min = A[i], and finally, edit the if statement from this:

if (A[i] < min) {
    ...
}

to this:

if (A[i] < A[minPosition]) {
    ...
}

CodePudding user response:

You have 2 variables that are doing the same job :

i) min which keeps track of the minimum in the array

ii) minPosition which is index of the min value.

You can simply compare everytime with the element at minPosition and swap it in the end.

class Main {
    public static void main(String args[]) {

        int[] A = { 13, 5, 2, 0, 3, 1, 21, 1, 8 };

        for (int k = 0; k < A.length - 1; k  ) {

            // int min = A[k];
            int minPosition = k;

            for (int i = k   1; i < A.length; i  ) {
                if (A[i] < A[minPosition]) {

                    minPosition = i;
                }
            }
            int temp = A[k];
            A[k] = A[minPosition];
            A[minPosition] = temp;
        }

        // for (int i = 0; i < A.length; i  ) {
        System.out.println(Arrays.toString(A));
        // }
    }
}
  •  Tags:  
  • java
  • Related