正如标题所说。我必须编写一个运行所有三种排序方法(冒泡、插入、选择)的代码。到目前为止,我已经准备好了气泡部分,但我不知道如何让它工作,因为在声明方法时必须定义一个变量,以便获得返回值。但我需要它返回方法外部定义的变量。有没有可能的方法来做到这一点?请记住,我还需要在另外两个方法中再次使用相同的值。
import java.util.Scanner;
public class Sorting {
static int d = 0;
static int c = 0;
static int n = 0;
static int swap = 0;
static int array[] = new int[n];
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Number of elements: ");
n = scan.nextInt();
System.out.print("Enter " + n + " elements: ");
for (c = 0; c < n; c++)
array[c] = scan.nextInt();
}
static void BubbleSort(int[] a) { //this line!!
for (c = 0; c < ( n - 1 ); c++) {
for (d = 0; d < n - c - 1; d++) {
if (array[d] > array[d+1])
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
System.out.print("Bubble sort: ");
for (c = 0; c < n; c++)
System.out.print(array[c] + " ");
}
}
最佳答案
很难理解你在问什么:
BubbleSort
方法采用int[] a
参数,但从不使用它main
方法将数字读取到数组中,但从不调用BubbleSort
- 您询问的是
BubbleSort
的返回值,但该方法被声明为void
,并且它修改了array
的内容,一个静态
变量:这个方法似乎并不打算返回任何东西,而是就地对数组进行排序 - 许多未使用的变量
- 许多变量在类中声明为静态,但它们可以是方法中的局部变量,其中一些在
for
循环中是局部的
解决上述问题后, 您的实现会更有意义,如下所示:
import java.util.Scanner;
public class Sorting {
public static void main(String[] args) {
int n, c;
Scanner scan = new Scanner(System.in);
System.out.print("Number of elements: ");
n = scan.nextInt();
int[] array = new int[n];
System.out.print("Enter " + n + " elements: ");
for (c = 0; c < n; c++) {
array[c] = scan.nextInt();
}
BubbleSort(array);
}
static void BubbleSort(int[] array) {
int n = array.length;
for (int c = 0; c < (n - 1); c++) {
for (int d = 0; d < n - c - 1; d++) {
if (array[d] > array[d + 1]) {
int swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
}
}
}
System.out.print("Bubble sort: ");
for (int c = 0; c < n; c++) {
System.out.print(array[c] + " ");
}
}
}
关于java - 在方法外部定义变量并获取其返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33400759/