Reputation: 2770
Java Day 1 from c#. Just playing around with java (just for fun) and thought this example was interesting, the thing that gets me is how does bubblesort method access intArray? ok I know its being passed as a variable.. but its modifying the original array? I could understand of the bubblesort method printed the new array, but its the original method? Cool, but now sure how/why this is allowed? (hope I explained this properly)
public class HelloWorld {
public static void main(String[] args) {
//create an int array we want to sort using bubble sort algorithm
int intArray[] = new int[]{5,90,35,45,150,3};
//print array before sorting using bubble sort algorithm
System.out.println("Array Before Bubble Sort");
for(int i=0; i < intArray.length; i++)
System.out.print(intArray[i] + " ");
//sort an array in descending order using bubble sort algorithm
bubbleSort(intArray);
System.out.println("");
//print array after sorting using bubble sort algorithm
System.out.println("Array After Bubble Sort");
for(int i=0; i < intArray.length; i++)
System.out.print(intArray[i] + " ");
}
private static void bubbleSort(int[] intArray){
int n = intArray.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(intArray[j-1] < intArray[j]){
//swap the elements!
temp = intArray[j-1];
intArray[j-1] = intArray[j];
intArray[j] = temp;
}
}
}
}
}
Upvotes: 1
Views: 107
Reputation: 925
Strictly talking, you are not modifying the array, you are moving its contents within positions
[1,3,2,4] => [1,2,3,4] is the same 4 lenght array but the content of the 2nd and 3rd position got they value changed.
Upvotes: 0
Reputation: 272467
Arrays are object types in Java, and so are accessed by reference. You pass a reference* to the original array when you call the method, so the method accesses (and modifies) the original array.
* To all the sharp-eyed pedants, I'm being very careful to avoid the "you pass by reference in Java" fallacy.
Upvotes: 4