ralston3 ralston3 - 6 months ago 7
Java Question

Assigning multiple values to multiple variables in a single line

I'm trying to write the Java equivalent of the following Python Inversion-Sort algorithm:

import numpy as np

def main(items):

for i in range(1, len(items)):
j = i
while j > 0 and items[j] < items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
j -= 1

print(items)

main(np.array([4, 78, 23, 24, 56, 7, 9]))


This is the Java version:

import java.util.Arrays;

public class Sorters {

public static void main(String args[]) {

Sorters sort = new Sorters();
int[] items = {4, 78, 23, 24, 56, 7, 9};
sort.insertionSort(items);
}

public void insertionSort(int[] items) {

for(int i=1 ; i<items.length ; i++) {
int j = i;
while(j>0 && items[j] < items[j-1]) {
items[j] = items[j-1]; // These two lines are
items[j-1] = items[j]; // causing the error
j -=1;
}
}
System.out.println("Sorted array: " + Arrays.toString(items));
}
}


I've narrowed the issue down to the two lines that are commented as such, above (in the Java method).

If I give the Python function this array:
[4, 78, 23, 24, 56, 7, 9]
(for example), everything works fine. However, if I give the same array to the Java method, I get this in return:
[4, 78, 78, 78, 78, 78, 78]
.

Could someone tell me how to write the Java equivalent of Python's
items[j], items[j-1] = items[j-1], items[j]
? Explanations welcomed. Thanks.

Answer

That's because you need to use a temp variable to store one of the values when you swap between the items[j] with items[j-1]. It should be something like that:

int temp = items[j];
items[j] = items[j-1];
items[j-1] = temp;

What happens is that you lose the original value so each iteration of the loop you get to copy into items[j] the value of items[j-1].

That's how you got your output.

Comments