So I have a quick_sort method that I am testing out like this:
public static void main(String[] args){
int x[] = {5,4,9,6,3,4,11,99,3,4,5,2,4,7,8,34,5,34543,545,454};
quick_sort(x,0,x.length-1);
System.out.println(Arrays.toString(x));
System.out.println(Arrays.toString(quick_sort(x,0,x.length-1)));
}
The output of this method is:
[5, 4, 9, 6, 3, 4, 11, 99, 3,4 ,5 ,2, 4, 7, 8, 34, 5, 34543, 545, 454]
[2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 7, 8, 9, 11, 34, 99, 454, 545, 34543]
My question is, I thought java was pass-by-value and that arrays were Objects. So i don't see why both of my outputs are not sorted. Why is only the second one, where I return array, printing out as sorted? When i pass x into the function shouldn't i just receive a copy of that pointer that still points to the same object in the heap? So any changes i make to that array should be modified for the original pointer.
edit:
I figured out that it has something to do with the fact that x is a literal. If i declare x as a new int[] in fill it manually, then both outputs seem to work fine.
Here is my quicksort:
public static int[] quick_sort(int arr[], int left, int right) {
if(left==right)
return arr;
int holdLeft = left;
int holdRight = right;
int partition = left + (right-left)/2;
while(left<right){
while(arr[left] < arr[partition])
left++;
while(arr[right]>arr[partition])
right--;
if(left <= right){
swap(arr,left,right);
left++;
right--;
}
}
if (holdLeft < right)
quick_sort(arr,holdLeft, right);
if (left < holdRight)
quick_sort(arr,left, holdRight);
return arr;
}