-2

I just have a question regarding my following code for quicksort in Java.

public class QuickSort{

public void sort(int array[]){
   quickSort(array,0,array.length-1);
}

public void quickSort(int array[], int left, int right){
    int index = partition(array,left,right);
    if(left<index-1){
        quickSort(array,left,index-1);  
    }
    if(index<right){
        quickSort(array,index,right);
    }
}

public int partition(int array[], int left, int right){
    int pivot = array[(left+right)/2];
    while(left<=right){
        while(array[left]<pivot){
            left++;
        }
        while(pivot<array[right]){
            right--;
        }

        if(left<=right){
            int temp=array[left];
            array[left]=array[right];
            array[right]=temp;
            left++;
            right--;
        }
    }
    return left;
}

public static void main(String args[]){
     int iArr[] = {23,44,1,2009,2,88,123,7,999,1040,88};
    QuickSort ms = new QuickSort();
    ms.sort(iArr);

    for(int i=0;i<iArr.length;i++){
        System.out.println(iArr[i]);
    }
}}

In the above code, I pass an array to a method for sorting which does not return anything. Hence, the original array in the main method must be still unsorted. But, when I try to print the values of the original array in the main method after calling sort method, they are somehow sorted.

How can the array in the main method be sorted, when I have not returned anything from the sort method. I know the scope is only restricted to the method.

Please explain me.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Yogi
  • 33
  • 1
  • 7

1 Answers1

1

It is because java arrays are reference types, so you're only passing a reference of the array to the method.

A reference essentially is an address of where the actual array data is located in memory

When you call quicksort, it copies the address of the array, but It doesn't copy the data at that address.

Because of this, the elements that you see in the calling method, are the same array elements that you're modifying in the quicksort method.