기술 면접 대비/자료구조

[Java로 배우는 자료구조] 값에 의한 호출 (Call by Value)

김또롱 2020. 8. 10. 21:43
2020.08.10 오늘의 공부

 

[Java로 배우는 자료구조] 제1-2장: 메서드 호출과 프로그램의 기능적 분할 (2/4)

https://www.inflearn.com/course/java-%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0/lecture/7435?tab=curriculum

 

Java로 배우는 자료구조 - 인프런

Java 언어의 문법 + 기본적인 프로그래밍 스킬 + 자료구조를 동시에 학습해보세요 초급 프로그래밍 언어 Java 자료구조 알고리즘 온라인 강의 java 자료구조

www.inflearn.com

 


 

메서드를 사용하여 버블 정렬을 해보자.

 

package Section02;

public class Code18 {

	public static void main(String[] args) {
		int [] array = {10,3,5,2,6,9,7};
		
		bubbleSort(array.length, array );
	
		for(int i : array) {
			System.out.print(i+" ");
		}
	}
	
	static void bubbleSort(int n, int[] arr) {
		for(int i = n-1; i>0; i--) {
			for(int j=0; j<i; j++ ) {
				if(arr[j]>arr[j+1]) {
					int tmp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = tmp;
				}
			}
		}
	}

}

 

결과

 

정렬이 잘 되는 것을 볼 수 있다.

 

그렇다면 

 

int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;

 

이 부분도 메서드로 바꾸었을 때 정렬이 잘 될까?

 

package Section02;

public class Code18_2 {

	public static void main(String[] args) {
		int [] array = {10,3,5,2,6,9,7};
		
		bubbleSort(array.length, array );
	
		for(int i : array) {
			System.out.print(i+" ");
		}
	}
	
	static void bubbleSort(int n, int[] arr) {
		for(int i = n-1; i>0; i--) {
			for(int j=0; j<i; j++ ) {
				if(arr[j]>arr[j+1]) {
					swap(arr[j], arr[j+1]);
				}
			}
		}
	}
	
	static void swap(int a, int b) {
		int tmp = a;
		a = b;
		b = tmp;
	}

}

 

 

결과

 

정렬이 하나도 되지 않았다.

 

왜 그럴까?

 

값에 의한 호출 (Call by Value)

 

swap(arr[j], arr[j+1]); 의 매개변수와 

 

static void swap(int a, int b) {
int tmp = a;
a = b;
b = tmp;
}

 

의 매개변수는 별개의 변수이다.

 

즉, 값을 복사해서 주는 것!

 

a, b가 바뀐다고 arr[j], arr[j+1]가 바뀌지 않는다.

 

서로 저장된 주소가 다르기 때문이다.

 

출처 : https://programist.tistory.com/entry/C-%EC%96%B8%EC%96%B4-Call-by-Value%EA%B0%92%EC%97%90-%EC%9D%98%ED%95%9C-%ED%98%B8%EC%B6%9C-Call-by-Reference%EC%B0%B8%EC%A1%B0%EC%97%90-%EC%9D%98%ED%95%9C-%ED%98%B8%EC%B6%9C%EC%9D%98-%EC%9D%B4%ED%95%B4

 

위의 그림을 보면 변수 a의 주소가 다른 것을 알 수 있다.

 

이게 바로 값에 의한 호출이다.

 

이와 반대되는 개념이 바로 참조에 의한 호출이다.

 

참조에 의한 호출은 C와 Java에선 지원하지 않는다.

 

C++에서는 지원을 한다.