这是一个冒泡排序算法的Java实现,我使用了另一个带有交换方法的类,当我在交换器类中不使用构造函数但是根本不交换数组时,这段代码工作正常一个构造函数存在。
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]);
}
}
但是当我使用构造函数来指定我的&#39;的x和y的值时。对象,此代码根本不交换任何元素。
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]);
}
}
两个代码的唯一区别是存在一个构造函数,用于为实例变量赋值。
第一个代码具有值的手动赋值,而第二个代码使用构造函数。
答案 0 :(得分:2)
你基本上是将这两个数字交换两次,因此根本不交换它们:
swapper s = new swapper(a[j],a[j+1]); // this assigns a[j] to s.x and a[j+1] to s.y
s.swap(); // this swaps s.x and s.y
a[j] = s.y; // this assigns the original value of s.x (a[j]) to a[j]
a[j+1] = s.x; // this assigns the original value of s.y (a[j+1]) to a[j+1]
为了使交换按预期工作,请将其更改为:
swapper s = new swapper(a[j],a[j+1]);
s.swap();
a[j] = s.x;
a[j+1] = s.y;