This is a Java implementation of Bubble sort algorithm, I have used another class with a swap method and this code works fine when I don't use a constructor in my swapper class but does not swap the array at all if a constructor is present.
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
class swapper {
int x, y;
void swap() {
int temp = x;
x = y;
y = temp;
}
}
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
int swaps = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
swaps++;
swapper s = new swapper();
s.x = a[j];
s.y = a[j + 1];
a[j] = s.y;
a[j + 1] = s.x;
}
}
}
System.out.println(
"Array is sorted in "
+ swaps
+ " swaps.\nFirst Element: "
+ a[0]
+ "\nLast Element: "
+ a[n - 1]);
}
}
But when I use a constructor to assign values of x and y of my 's' Object, this code does not swap any element at all.
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
class swapper {
int x, y;
swapper(int a, int b) {
x = a;
y = b;
}
void swap() {
int temp = x;
x = y;
y = temp;
}
}
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
int swaps = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
swaps++;
swapper s = new swapper(a[j], a[j + 1]);
s.swap();
a[j] = s.y;
a[j + 1] = s.x;
}
}
}
System.out.println(
"Array is sorted in "
+ swaps
+ " swaps.\nFirst Element: "
+ a[0]
+ "\nLast Element: "
+ a[n - 1]);
}
}
The only difference in both the codes is the presence of a constructor to assign values to the instance variables.
The first code has manual assignments of values whereas the second code uses a constructor.