2014-01-30 66 views
0

我有一个任务来计算选择排序中的赋值和比较。出于某种原因,我的分配计数器不增加。我已经尝试在swap之上添加它,并尝试将其纳入交换方法 - 无济于事。任何想法,为什么它不工作?计数器不递增

更新:计数器不适用于本

  Integer[] test = {1, 0, 4, 2}; 
      selectionSort(test); 

工作,但它的工作,为此:

selectionSort(new Integer[] {1, 0, 4, 2}); 

任何人都知道为什么吗?

public static void selectionSort(Integer[] array) 
{ 
    int assignmentCounter = 0; 
    int comparisonCounter = 0; 
    int i, j; 

    for(i = 0; i < array.length; i++) 
    { 
     int minIndex = i; 
     for(j = i + 1; j < array.length; j++) 
     { 
      comparisonCounter++; 
      if(array[j].compareTo(array[minIndex]) < 0) 
      { 
       minIndex = j; 
       assignmentCounter++; 
       swap(array,minIndex,i); 
      } 
     } 
    } 
    System.out.println("Selection Sort Comparisons: " + comparisonCounter + "\nSelection Sort Assignments: " + assignmentCounter); 
    for(int k = 0; k < array.length; k++) 
     { 
      System.out.print(array[k] + ", "); 
     } 
     System.out.println("\n\n "); 
} 

谢谢!

+4

您的数组是排序? –

+0

你现在得到的assignmentCounter的价值是什么? –

+2

它对我来说运行良好。 –

回答

0

当我运行这个

public static void main(String[] args) { 
    selectionSort(new Integer[] { 1, 0, 4, 2 }); 
} 

我得到的输出

Selection Sort Comparisons: 6 
Selection Sort Assignments: 2 
0, 1, 2, 4, 

你可能期待一个static或其他局部变量也称为assignmentCounter改变?

selectionSort中声明的变量assignmentCounter对于该方法是本地的。它外面没有任何东西可以看到它。

+0

不可以。除了该方法的本地变量之外,没有其他变量。我的显示器正好是你的,除了我的第二个数字是0.因此我感到沮丧,因为我无法继续实际做我的任务! – MayNotBe

+0

@MayNotBe尝试清理并重新编译您的项目。如果它仍然不起作用,我会使用调试器。 –

+0

看看这个:'Integer [] test = {1,0,4,2}; \t \t selectionSort(test); \t \t selectionSort(new Integer [] {1,0,4,2});'我的方式不增加,你的方式。为什么你认为? – MayNotBe