-2

i want to sort both 1 Dimensional and 2 Dimensional array without using temp variable in java. How to do it can anyone suggest

user3182420
  • 21
  • 1
  • 3
  • Why? The temporary variable makes it much easier... – abiessu Mar 03 '14 at 19:44
  • Use the old triple-xor technique. (Of course, you still need temps for your array indexes.) – Hot Licks Mar 03 '14 at 19:45
  • how about using a global variable? ;) bubble sort is predicated on storing nodes and swapping... – T McKeown Mar 03 '14 at 19:45
  • A) By not using bubblesort (unless that's your task specifically) B) you can't swap array elements without a temporary variable (unless it's an `int` or so and you want to do ugly looking xor magic http://stackoverflow.com/a/3912726/995891) – zapl Mar 03 '14 at 19:46
  • @abiessu it was asked in interview to sort without using temporary variable – user3182420 Mar 03 '14 at 19:56
  • Did you try anything or do any research? Your question is a little lacking.. – Mike Mar 03 '14 at 20:33

1 Answers1

4

If you are using integer(numeric in general) array you can use the following element change approach in sort algorithm:

int x = 10;
int y = 23;

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

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

output will be:

x = 23
y = 10
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
  • an array can contain number of elements....not possible to do it with this code Ashot – user3182420 Mar 03 '14 at 19:53
  • @user3182420, of course I know. But this is only the part of algorithm, when will be switched a[i] and a[j]. I wrote "you can use the following element change approach". The algorithm can select you (bubble sort) for example. You can find it here http://www.programmingsimplified.com/java/source-code/java-program-to-bubble-sort and instead of using `swap` variable use provided approach. – Ashot Karakhanyan Mar 03 '14 at 19:55