Question

Trying to break down this simple pseudocode into java code

for j <- 2 to n
    do key <- A[j]
       i <- j - 1
    while i > 0 and A[i] > key
          do A[i+1] <- A[i]
             i <- i - 1
    A[i + 1] = key

It's just an insertion sort example, but I'm confused as to what the call for "do" without a while is after the first do while.

I have this so far:

for(int j = 2; j < arrayToSort.size(); j++)
    {
        int key, i;
        do
        {
            key = arrayToSort.get(j);
            i = j -1;
        }while(i > 0 && arrayToSort.get(i) > key);
    }
Was it helpful?

Solution

Actually you are confusing the while loop with do-while. The first do here is not a part of while. So, it's not a do-while loop.

It's just telling to do the shown assignment inside the for loop, before the while loop starts.

So, the equivalent code would be like:

for (int j = 2; j < n; ++j) {
    int key = A[j];
    int i = j - 1;

    while (i > 0 && A[i] > key) {
        A[i+1] = A[i];
        i = i - 1;  // can be replaced with '--i'
    }
    A[i + 1] = key
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top