0

我正在尝试交换数组 b 的值并将一个值存储在 k 中,以便后置条件 b [0...h] <= 9 和 b[k+1..] > 9 为真。

到目前为止我有这个:

for ( int b = 0; k!= b.length; k = k+1 ) {
    int p = k+1;
    for ( int h= k+1; h != b.length; h= h+1 ) {
       if ( b[h] < b[p] ){ 
           p= h;
       }
    }

    int t = b[h]; 
    b[h]= b[p]; 
    b[p]= t;
}
4

1 回答 1

0

据我了解,您正在尝试做的是获取一个数组int,对其进行排序,然后找到索引 where n > 9

实现这一点的最简单方法是Arrays.sort首先对数组进行排序,然后一个简单的 for 循环将显示最后一个索引的位置。然后,您可以将数组一分为二,因此第一个数组包含所有值 <= 9,第二个数组包含所有 >9

这是一个例子:

public static void main(String[] args) {

    //Test data
    int[] arrayOfInt = {11, 42, 24, 1, 8, 9, 10, 15, 8, 29, 9, 34 };

    //Sort the array
    Arrays.sort(arrayOfInt);

    int index = 0;

    //This will get you the index where the last number is <= 9
    for (int i = 0; i < arrayOfInt.length; i++) {
        if (arrayOfInt[i] <= 9)
            index = i + 1;
    }

    //Now you know that from arrayOfInt[0] -> arrayOfInt[index] will be <= 9
    //If you want to use them seperately, you can just split the array into two
    int[] lessThanOrEqualToNine = Arrays.copyOfRange(arrayOfInt, 0, index);
    int[] greaterThanNine = Arrays.copyOfRange(arrayOfInt, index, arrayOfInt.length);

    System.out.println(Arrays.toString(lessThanOrEqualToNine));
    System.out.println(Arrays.toString(greaterThanNine));

    /* Prints the output:
     *  [1, 8, 8, 9, 9]
     *  [10, 11, 15, 24, 29, 34, 42]
     */
}
于 2012-04-18T07:39:59.257 回答