0

There is a specific input (Array) and I need to say what will be the output in line 14, what will be the output in line 17 etc. That's why I tried to convert the given pseudocode to java code, so I see from code what the output will be. Task also says that the pivot element is the element on the very left side of the divided array.

Pseudocode:

func int divide(S array; l, r integer){
val := S[r];
i := l;
j := r-1;
repeat
  while (S[i] <= val and i < r)
    i := i+1;
  end while;
  while (S[j] >= val and j > 1)
    j := j-1;
  end while;
  if i < j then
     swap (S[i], S[j]);
  end if;
until i >= j;
swap (S[i], S[r]);
return i;
}

Java Code:

public class Testt {
    public static void main (String[] args)
    {
        int[] S = {2, 10, 6, 7, 13, 4, 1, 12, 5, 9};
        int l = 0;
        int r = 0;
        int val;
        int i = 0;
        int j = 0;

        val = S[r];
        i = l;
        j = r-1;

        do
        {
            while (S[i] <= val && i < r) {
                i = i+1;
            }
            while (S[j] >= val && j > 1) {
                j = j - 1;
            }
            if (i < j) {
                S[j] = S[i];
            }
        } while (i >= j);
        S[r] = S[i];
        System.out.println(i);
    }
}
frytkii
  • 31
  • 2
  • Tunaki, how can a question like _Did I convert X to Y correctly?_ be an **exact duplicate** of a question like _What causes Z?_ ? This guy wants to know, if he did the conversion from pseudo code to java code correctly... (even if the underlying answer might be that he gets an ArrayOutOfBoundException ... he still does not know if his conversion is correct or not). – Maurice Müller Jun 10 '16 at 14:10
  • Your java code is not correct. The swap operation does not actually swap the two values, but overrides the second value with the first one. – Maurice Müller Jun 10 '16 at 14:12
  • Regarding the swap operation, try something like [this](https://en.wikipedia.org/wiki/Swap_(computer_programming)#Using_a_temporary_variable). – Maurice Müller Jun 10 '16 at 14:14
  • The code indeed fails with an `java.lang.ArrayIndexOutOfBoundsException: -1`, for that, the linked question will explain how to solve it and correct the algorithm. – Tunaki Jun 10 '16 at 17:27
  • Yes, he gets an exception, but solving that will only solve half of the problem. He still has other mistakes in is code. For that it is not an exact duplicate, because the linked answer will provide no information how to solve the other mistakes. – Maurice Müller Jun 13 '16 at 10:01

0 Answers0