gpt4 book ai didi

java - 我想通过使用另一个带有交换方法的类而不是通常可用的通用交换函数来交换两个数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:52:01 26 4
gpt4 key购买 nike

<分区>

这是冒泡排序算法的 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]);
}
}

但是当我使用构造函数为我的“对象”分配 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]);
}
}

这两种代码的唯一区别是存在一个构造函数来为实例变量赋值。

第一段代码手动赋值,而第二段代码使用构造函数。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com