首页 > 解决方案 > 为什么我的程序没有在我的公共 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);
  }
}

标签: javamethods

解决方案


因为 int 是原始类型,所以 count 变量不会在您的函数中被修改。

改变

ob.bubbleSort(bub, count); 

count = ob.bubbleSort(bub, count);

推荐阅读