我正在编写一个程序,在主类中生成10k个随机整数,然后对其进行排序,返回数组排序次数的计数。问题是,即使我将该方法公开并返回计数,但在运行它之后,它总是显示为0。
方法
public int bubbleSort(int bub[], int count){
int n = bub.length;
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(bub[j]>bub[j+1]){
int temp = bub[j];
bub[j] = bub[j+1];
bub[j+1] = temp;
count++;
}
return count;
}
void printArray(int bub[]){
int n = bub.length;
for(int i=0;i<n;i++){
System.out.print(bub[i] + " " );
}
}
}主类
import java.util.Random;
class Main{
public static void main(String args[]){
Random rd = new Random();
Bubble ob = new Bubble();
int count=0;
int[] bub = new int[10000];
for(int i=0;i<bub.length;i++){
bub[i] = rd.nextInt(100);
}
ob.bubbleSort(bub, count);
System.out.println(count);
System.out.println("sorted array");
ob.printArray(bub);
System.out.println("number of times array was sorted " + count);
}
}发布于 2021-02-11 17:34:24
因为int是一个基本类型,所以在函数中计数变量不会被修改。
变化
ob.bubbleSort(bub, count); 至
count = ob.bubbleSort(bub, count);https://stackoverflow.com/questions/66159765
复制相似问题