Java Program to Swap Two Numbers
Problem Statement: Given two integers m and n. The goal is simply to swap their values in the memory block and write the java code demonstrating approaches.
Illustration:
Input : m=9, n=5
Output : m=5, n=9
Input : m=15, n=5
Output : m=5, n=15
Here 'm' and 'n' are integer value
Approaches:
There are 3 standard approaches to swap numbers varying from space and time complexity.
1.Creating an auxiliary memory cell in the memory.
2.Without creating any auxiliary(additional) memory cell
**3.Using exclusive OR (Bitwise XOR) operator(TBD)
4: Using arithmetic operators (TBD)
**
Approach 1: Swapping the Values Using Third Variable
A memory cell will be created in the memory of the same type occupying same memory in stack area of memory. During execution, it holds on one value to replace others values, once desired execution is completed its value is assigned to already existing second variable. Once scope for the variables are three variables are released from memory cell. This variable is called temporary variable or sometimes referred as catalyst as the involvement in output is not even traced out but executions will halt to produce desired result above witnessed.
// Java Program to Swap Two values using third variable
// using temp variable
// Importing generic libraries
import java.util.*;
class GFG {
// Function to swap two numbers
// Using temporary variable
static void swapValuesUsingThirdVariable(int m, int n)
{
// Swapping the values
int temp = m;
m = n;
n = temp;
System.out.println("Value of m is " + m
+ " and Value of n is " + n);
}
// Main driver code
public static void main(String[] args)
{
// Random integer values
int m = 9, n = 5;
// Calling above function to
// reverse the numbers
swapValuesUsingThirdVariable(m, n);
}
}
Output
Value of m is 5 and Value of n is 9
*Approach 2: Swapping the Values Without Using Third Variable by using sum and differences concepts of math.
*
Algorithms: There are 3 standard steps as listed below:
1.Difference of second number from the first number is stored in memory cell where first number was already stored.
2.Sum of both the numbers is stored in second memory cell(number).
3.Difference of first number from the second is computed and stored in memory cell where at initial first value was stored.
// Java Program to swap the two values
// without using third variable
// Importing generic Java libraries
import java.util.*;
class GFG {
// Function to swap values of two numbers
// without creating temp variable
static void swapValuesWithoutUsingThirdVariable(int[] values) {
// Steps as listed in algorithm
// Difference of 2nd from 1st
// is stored in first variable
values[0] = values[0] - values[1];
// Sum is stored in second variable
values[1] = values[0] + values[1];
// Difference of 1st from 2nd
// is replaced in first variable
values[0] = values[1] - values[0];
}
// Main driver method
public static void main(String[] args) {
// Random numbers of integer type
int[] values = {9, 5};
// Above function is called in main
// to swap values of numbers
swapValuesWithoutUsingThirdVariable(values);
// Print swapped values
System.out.println("Value of m is " + values[0] + " and Value of n is " + values[1]);
}
}
Output:
Value of m is 5 and Value of n is 9
** Note: Swap the Numbers without using any extra variable
m=m+n;
n=m-n;
m=m-n;
**
Approach 3: Swapping the Values Using Operator(TBD)
Bit-wise operators are used to perform manipulation of individual bits of a number. They can be used with any of the integral types (char, short, int, etc). They are used when performing update and query operations of Binary indexed tree.
This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it gives 0.
Illustration:
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR Operation of 5 and 7
0101
^ 0111
0010 = 2 (In decimal)
This is the most optimal method as here directly computations are carried on over bits instead of bytes as seen in above two methods. Here’s a Java program to show internal working –
// Java Program to swap the two values
// using XOR Operator
// Importing generic Java libraries
import java.io.*;
class GFG {
// Function to swap values of two numbers
// using XOR operator
static void swapValuesUsingXOROperator(int m, int n)
{
// Logic of XOR operator
m = m ^ n;
n = m ^ n;
m = m ^ n;
System.out.println("Value of m is " + m
+ " and Value of n is " + n);
}
// Main driver method
public static void main(String[] args)
{
// Random two integer numbers
// to get swapped
int m = 9, n = 5;
// Calling the function in main method
// to get above integer numbers swapped
swapValuesUsingXOROperator(m, n);
}
}
Output
Value of m is 5 and Value of n is 9
Complexity of the above method:
Time complexity: O(1) as it is doing constant operations
Auxiliary Space: O(1)
*Approach 4: Using arithmetic operators *(TBD)
This is simplest way to swap the numbers without using any 3rd variable also swap the numbers in single line. In this approach will follow the simple expression to swap the numbers i.e., a = (a + b) – (b = a); Suppose we have value a=10, b=22, if we put these values in mentioned expression then it swap the values. It follows BODMAS rule then first bracket (a+b) i.e., (10+22)=32 then it will solve another bracket (b=a) which simply put the value of a in b i.e., b=10. Now it will subtract 32-10 i.e., a=22. In this way we can swap the numbers easily.
public class HelloWorld{
public static void main(String []args){
int a=10,b=22;
System.out.println("Before swapping Value of a is " + a
+ " and Value of b is " + b);
a = (a + b) - (b = a);
System.out.println("After Swapping Value of a is " + a
+ " and Value of b is " + b);
}
}
Output
Before swapping Value of a is 10 and Value of b is 22
After Swapping Value of a is 22 and Value of b is 10
Complexity of the above method:
Time complexity: O(1)
Auxiliary Space: O(1)
REFERENCE:https://www.geeksforgeeks.org/java-program-to-swap-two-numbers/
Java Collections swap() Method(TBD)
The swap() method of Java Collections class is used to swap the elements at the specified positions in the specified list.
Syntax
Following is the declaration of swap() method:
public static void swap(List<?> list, int i, int j)
**list-It is the list in which we will swap the elements.
i-It is the index of one element to be swapped.
j-It is the index of the other element to be swapped.**
Returns
The swap() method does not return anything.
Example 1:
import java.util.*;
public class CollectionsSwapExample2 {
public static void main (String[] args) {
//Create a list with items
List<Integer> list = Arrays.asList(44, 55, 99, 77, 88, 66);
System.out.println("List before swapping: "+list);
Collections.swap(list, 2, 5);
System.out.println("List after swapping: "+list);
}
}
Output:
List before swapping: [44, 55, 99, 77, 88, 66]
List after swapping: [44, 55, 66, 77, 88, 99]
REFERENCE:https://www.tpointtech.com/java-collections-swap-method
PROGRAM ABOUT interchangearrayposition AND find position
package afterfeb13;
public class interchangearrayposition {
public static void main(String[] args) {
int[] score = { 90, 80, 70, 100, 49 };
int max = 0;
int max_index = 0;// compare to count
for (int i = 0; i < score.length; i++) {
if (score[i] > max) {
max = score[i];
max_index = i;// equal to count++
}
System.out.print(score[i] + " ");
}
System.out.println();
System.out.println(max_index+" match score = "+max);
int len = score.length - 1;// score length index 0 1 2 3 4
int temp = score[max_index];// storing temp index 3 in int temp for swapping
score[max_index] = score[len];// changing score[max_index](3) to score[len](4)
score[len] = temp;// index[3] in temp, then change score[len]=3
// System.out.println(score[4]);
for (int i = 0; i < score.length; i++) {
System.out.print(score[i] + " ");// changed index will be printed
}
}
}
Output:
90 80 70 100 49
3 match score = 100
90 80 70 49 100
Top comments (0)