1

I am new to programming and I was trying to implement Quicksort on java.My code seems is working perfectly. But there is something I can't understand The static method called 'partition'(as you can see below in the code snippet) returns an 'int'type variable and manipulates the array 'arr'. Now when I call QuickSortAlgo method with input as 'arr', why is this 'arr' array that goes inside the QuickSortAlgo method the manipulated/modified array (modified in the method 'partition')? When the method 'partition' ends shouldnt the array 'arr'(which was modified in partition) be forgotten since the method 'partition' only returns an 'int'?

public static double[] QuickSortAlgo(double arr[],int low, int high){
            if(low<high){
                int pi=partition(arr,low,high);
                QuickSortAlgo(arr, low, pi-1);  // Before pi
                QuickSortAlgo(arr, pi+1, high); // After pi
            }
user3503589
  • 139
  • 8
  • how does it manipulate/modify arr? – Stultuske Mar 20 '19 at 13:38
  • partition is the function that modifies data. QuickSortAlgo, simply instructs partition how to do it. Once partition modifies the data, it tells QuickSortAlgo what it did, so that QuickSortAlgo can know how to proceed. – Dylan Mar 20 '19 at 13:39
  • should 'arr' be 'forgotten'? what do you mean by forgotten? – Stultuske Mar 20 '19 at 13:40
  • And I apologize for not being very precise but I wasn’t sure how to precisely ask the question . – user3503589 Mar 20 '19 at 14:05

1 Answers1

1

Here:

public static double[] QuickSortAlgo(double arr[],int low, int high){

Your method QuickSortAlgo() (which should better be named runQuicksort() for example) receives a reference pointing to an array of double values.

It then passes on that reference:

int pi=partition(arr,low,high);

This means: both methods "see" the very same object in memory (that array of double numbers). There is just one thing in memory, and the return type of partition() doesn't have anything to do with that.

So, unless partition() first creates a NEW array and copies over content from the array passed to it, it simply works on the very same memory area that the sort method is "looking" at.

Beyond that, you probably want to learn about pass by value for java references.

GhostCat
  • 137,827
  • 25
  • 176
  • 248