given an array A of the integers 1,2,3,...,N and the character " "(space)
we want to sort it to be [1,2,3,...,N," "], where we can only swap integers with " ", but not with each other, so swap(3," ") is allowed while swap(1,2) is not.
My attempt at it was to denote the space be "-1", and search for it in O(N) time, then go over the array again from i=1 to N+1 and if I see for example A[2] = 7, I would swap A[7] with " ", then I'd swap A[2] with " " while keeping track of " "'s position since It's the only way to swap, that way 7 would end up at A[7] ( with the exception of index shifting)
The code I wrote is the following:
public static int[] arraySort(int[] array){
int space = 0;
for(int i = 0; i<array.length; i++ ){
if(array[i] == -1){
space = i;
}
}
for(int i = 0; i<array.length; i++){
if(array[i] != i+1 && array[i] !=-1){
swap(array, array[i]-1 , space);
space = array[i]-1;
swap(array, i, space);
space = i;
}
}
return array;
}
public static void swap(int[] arr, int ind1, int ind2){
int temp = arr[ind2];
arr[ind2] = arr[ind1];
arr[ind1] = temp;
}
It did work, however for input such as A[7,3,5,4,6,1,2,-1]
it failed, I'm aware that I might be sending an integer to the head of the array but I can't see why it wouldn't get back out since a different number goes there then it would eventually go to its position.
Help? or an idea of how to fix this( while still keeping it in O(N) time if possible?
"given an array , A , of the integers 1,2,3,...,N", this sounds like your array cannot contain negative integers, but then in your test case ([7,3,5,4,6,1,2,-1]), you're using a negative integer. Can the input array contain negative integers as well as positive integers, or only positive integers?