【发布时间】:2013-12-14 11:25:50
【问题描述】:
我写了一个类,它应该创建一个随机数组,并对其进行排序。我为每个方法编写了方法,每个方法中的代码都可以独立运行。但是当我一起使用它们时,我无法使用 sort 方法对随机方法创建的内容进行排序。有什么想法吗?
注意,如果有帮助的话,我正在使用 Java 进行编码并使用 NetBeans。而且我不想要更简单的编码方式,我只是想要帮助使其工作。
这是我的代码。
public class SortUtility {
private int[] num;
static Random rand = new Random();
private int c = 0;
private int swap = 0;
private int compare = 0;
private int p = 10;
private int[] b;
//private int[] ex;
public SortUtility() {
num = new int[p];
}
public SortUtility(int[] Startnum) {
int[] b = Startnum;
}
public int[] createRandomArray(int max, int min, int[] num) {
//private int [10] ex;
int [] ex = new int[num.length];
for (int i = 0; i < num.length; i++) {
num[i] = rand.nextInt(max + 1 - min) + min;
}
for (int i = 0; i < num.length; i++) {
ex[i] = num[i];
}
return ex;
}
public int[] sortArray1(int[] ex) {
int a;
printItems();
do {
c++;
for (a = 0; a < num.length - 1; a++) {
compare++;
if (num[a] > num[a + 1]) {
int temp = num[a];
num[a] = num[a + 1];
num[a + 1] = temp;
swap++;
System.out.println(num[2]);
}
}
printItems();
} while (c != num.length);
return num;
}
public void printItems() {
System.out.print("\nPass " + c + " Compares " + compare + " Swaps " + swap + " " + "items ");
for (int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
}
public int[] sortArray2(int[] ex) {
int a;
int swap2 = 0;
printItems();
do {
c++;
for (a = 0; a < num.length - 1 - (c - 1); a++) {
compare++;
if (num[a] > num[a + 1]) {
int temp = num[a];
num[a] = num[a + 1];
num[a + 1] = temp;
swap++;
}
}
if (swap2 < swap && swap2 != swap) {
if (swap2 < swap) {
swap2 = swap;
}
}
swap2++;
printItems();
} while (swap + 2 != swap2);
return num;
}
}
这是我的客户
package sortclient;
public class SortClient {
public static void main(String[] args) {
int[] num = {25, 7, 99, 14, 55, 3, 47, 6, 1};
SortUtility ds = new SortUtility();
//SortUtility j = new SortUtility(l);
SortUtility ab = new SortUtility();
int[] a = ab.createRandomArray(99, 0, num);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
ab.sortArray1(a);
}
}
这是我运行客户端时的结果:
run:
52
8
82
87
93
29
94
33
46
Pass 0 Compares 0 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 1 Compares 9 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 2 Compares 18 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 3 Compares 27 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 4 Compares 36 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 5 Compares 45 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 6 Compares 54 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 7 Compares 63 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 8 Compares 72 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 9 Compares 81 Swaps 0 items 0 0 0 0 0 0 0 0 0 0
Pass 10 Compares 90 Swaps 0 items 0 0 0 0 0 0 0 0 0 0 BUILD SUCCESSFUL (total time: 0 seconds)
这证明了随机数组方法有效并且排序有点有效
【问题讨论】:
-
您打印出随机数组,然后对它进行排序,您是否忘记了第二次打印?
-
您在这里有主要的变量名称混淆。例如,在 sort 方法中,您获取一个名为
ex的数组,然后打印并排序一个名为num的数组。在创建方法中,您获取一个名为num的本地数组,它会隐藏您的类变量,填充该数组并将其复制到另一个名为ex的本地数组中。您的代码无法正常工作的原因是您几乎在每个地方都使用了错误的变量。了解范围和阴影。
标签: java arrays class sorting methods