0

I'm trying to swap the values of array b and to store a value in k so that the postcondition b [0...h] <= 9 and b[k+1..] > 9 is true.

I have this so far:

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;
}
Gareth Davis
  • 27,701
  • 12
  • 73
  • 106

1 Answers1

0

From what I understand you're trying to do, is take an array of int, sort it, and then find the index where n > 9.

The easiest way to achieve this is by using Arrays.sort to first sort your array, and then a simple for loop will show where the last index is. You can then split the array in two, so the first array contains all values <= 9, and the second one contains all >9

Here's an example:

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]
     */
}
Deco
  • 3,261
  • 17
  • 25