0

我只是对如何实现这两种方法感到困惑,比如如何调用它们或使用它们?由于第一个是无效的,它是如何工作的?

有人请使用和数组并为我实现它或帮助我了解第一个 void 方法是如何工作的?

public static void insertionsort(int[] numbers) {
    for (int i = 0; i < numbers.length; i++) {
         int copyNumber = numbers[i];
         int j = i;
         while (j > 0 && copyNumber < numbers[j-1]) {
             numbers[j] = numbers[j-1];
             j--;
         }
         numbers[j] = copyNumber;
    }
}

public int[] InsertionSort(int[] data){
    int len = data.length;
    int key = 0;
    int i = 0;
    for(int j = 1;j<len;j++){
        key = data[j];
        i = j-1;
        while(i>=0 && data[i]>key){
            data[i+1] = data[i];
            i = i-1;
            data[i+1]=key;
        }
    }
    return data;
}
4

3 回答 3

1

具有返回类型的函数会做某事(执行代码)并将一些结果返回给调用该函数的代码。没有返回类型的函数执行一些代码但不返回结果(因为在大多数情况下不需要它)

考虑这两个函数:

public static int withResult( int someParameter)
{
    //execute some code here

    int someReturnValue = //result of the code above

    return someReturnValue;
}

public static void withoutResult( int someParameter)
{
    //execute some code here which produces no result which could be of interest to the caller (calling code)
} //end the function without returning anything

你可以这样称呼它:

int result;
result = withResult( 1234 );//executes the function and stores its return type in 'result'
withResult( 468 );//executes the function but does not store the return type anywhere ("throws it away")
withoutResult ( 1234 );//simply executes the function
result = withoutResult ( 5678 ); //this makes no sense because the function does not return anything
于 2013-11-09T04:36:15.237 回答
1

在java中,一切都是按值传递的,包括引用。在您的void方法中,传递了对数组的引用的值。因此,虽然您无法分配 newint []numbers,但您可以更改intsin numbers

于 2013-11-09T04:17:49.837 回答
0

第一种方法,返回 void(即不返回任何内容),将数组作为参数传递。传递的是对声明的数组的引用,并且在方法之外为其分配了内存。该方法对信息进行了适当的排序;当方法返回时,对该数组中的数据进行排序。

int[] myArray = getArrayInfo();       // assume this gets data in an array
WhateverClass.insertionSort(myArray); // this will sort that data

// at this point, myArray will be sorted
于 2013-11-09T04:13:59.333 回答