Java Puzzle 07 – Swap

Merhaba Arkadaslar,
Iki degiskenin swap/yer degistirme islemini genelde bir temporary/gecici degisken kullanarak yapariz. Bu swap/yer degistirme islemini temporary/gecici degisken kullanmadan da yapabiliriz.
Oncelikle temporary/gecici degisken kullandigimiz durumu inceleyelim;

SwapWithTemporary.java

package _07.swap;

public class SwapWithTemporary {

	public static void main(String[] args) {
		int x = 13;
		int y = 7;

		System.out.println("x:" + x + " y:" + y);

		x = x + y;
		y = x - y;
		x = x - y;

		System.out.println("x:" + x + " y:" + y);
	}
}

Temporary/gecici degisken kullanmadan ise su sekilde yapabiliriz;

SwapWithoutTemporary.java

package _07.swap;

public class SwapWithoutTemporary {
	public static void main(String[] args) {
		int x = 13;
		int y = 7;

		System.out.println(Integer.toBinaryString(x)); // 1101 // binary
		System.out.println(Integer.toBinaryString(y)); // 111 //binary

		System.out.println("x:" + x + " y:" + y);

		x = x ^ y;
		y = y ^ x;
		x = x ^ y;

		System.out.println("x:" + x + " y:" + y);

	}
}

^ , operatoru XOR islemi yapmamizi saglar.
http://en.wikipedia.org/wiki/XOR_swap_algorithm

13 un binary karsiligi 1101
7 nin binary karsiligi 111

xor ^ islemi yaptigimizda

x=x^y

1101
0111  xor
------
1010  

y=y^x

1010
0111
-----
1101

x=x^y
1010
1101
-----
0111

Bir baska yontem olarak ;
SwatWithMathOperation.java

public class SwatWithMathOperation {

	public static void main(String[] args) {
		int x = 13;
		int y = 7;

		System.out.println("x:" + x + " y:" + y);

		x = x + y;
		y = x - y;
		x = x - y;

		System.out.println("x:" + x + " y:" + y);
	}
}

Yazimi burada sonlandiriyorum.
Herkese bol Javali gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply to Levent Erguder Cancel reply

Your email address will not be published. Required fields are marked *