java - 为什么我的程序没有在我的公共 int 方法中返回计数整数?
问题描述
我正在编写一个程序,它在主类中生成 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);
}
}
解决方案
因为 int 是原始类型,所以 count 变量不会在您的函数中被修改。
改变
ob.bubbleSort(bub, count);
至
count = ob.bubbleSort(bub, count);
推荐阅读
- python - Python递归返回无,但我明确设置返回
- ios - 对于包含大量页面的 UIPageViewController,我们如何恢复当前可见页面的 UICollectionView 的 UI 状态?
- java - 如何访问我的 BigQuery 结果集的 cacheHit 属性?
- angular - 带有外部库的 Angular 项目不能使用 angular-cli 在 AOT 模式下编译
- kubernetes - Kubernetes 中的 Hyperledger Fabric:无法实例化链码
- python - 找不到 Rasa 自定义组件
- sql - PostgreSQL - WHERE 子句不起作用 - 未找到列名
- vue.js - 如何预渲染多个 Vue 应用页面?
- html - 如何更改文字样式?
- javascript - 需要替换变量值格式的正则表达式模式