Swapping using a third variable in Java -
what need use third variable swap numbers? sorry, don't it.
here sample code have sorting elements of array based on length of each element. can see here, using third variable, , swapping elements of array. have different implementation program works, found below example online, , understand swapping useful for? if explain me, great.
public class stringsort { public static void main(string[] args) { string[] arr = new string[] { "abcd", "dexter", "stringsortexample", "fruit", "apple","car" }; comparearrayelements(arr); system.out.println("the strings in sorted order of length are: "); (string sortedarray : arr) { system.out.println(sortedarray); } } public static void comparearrayelements(string[] arr) { string temp = ""; (int = 0; < arr.length - 1; i++) { (int j = i+1; j < arr.length; j++) { if (arr[i].length() > arr[j].length()) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } }
the short answer can't juggle in java!
think of each variable hand can "hold" 1 value; e.g. ball.
if have 2 hands , 2 balls, way switch balls opposite hands involves throwing 1 of balls in air (or that). there no "throw value air" operation in java.
if can't juggle need third hand (or other temporary holding place) swap balls. , in java terms, means temporary variable.
for record, found analogy useful when learning program. don't take far :-).
(in fact, if talking integers, there mathematical trick can use swap numbers ... involving xor ... doesn't work in general.)
Comments
Post a Comment