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]))
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));
}
}
[4, 78, 23, 24, 56, 7, 9]
[4, 78, 78, 78, 78, 78, 78]
items[j], items[j-1] = items[j-1], items[j]
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.