Home > Blockchain >  Can't sort the odd numbers in the array
Can't sort the odd numbers in the array

Time:09-08

I am really new to java (started learning 2 days ago). Sorry if this is a stupid question.I have an exercise to sort odd numbers in an ascending array. But it fails to sort. And this is my error. Thank you for your helpenter image description here

    package Java1;

import java.util.ArrayList;
import java.util.List;

public class StringB1 {
     public static void main(String[] agrs) {
            int arr[] = {1,3,4,6,9,7,8,2};
            for (int e : arr) {
                System.out.println(e);
            }
        }
    public static int[] sortArray(int[] array) {
        List<Integer> list = new ArrayList<>();
        for (int e : array) {
            if (e % 2 != 0) {
                list.add(e);
            }
        }
        list.stream().sorted();
        for (int i = 0; i < array.length; i  ) {
            if (array[i] %2 != 0){
                for (int j = 1; j < list.size(); j  ) {
                    array[i] = list.get(j);
                }
            }
        }
        return array;
    }
}

CodePudding user response:

Stream left incomplete

Your code:

list.stream().sorted(); 

… is flawed.

You left the stream incomplete, not yet resolved. The method Stream#sorted is documented as returning another stream.

To quote the Javadoc:

Returns a stream consisting of the elements of this stream …

This is a stateful intermediate operation.

Furthermore, the Javadoc never promised that the original source list would be affected.

Apparently you assumed that calling sorted on a stream would sort the source list. Programming by assumption rarely goes well. Before blindly calling methods, study the Javadoc. If not clear, search Stack Overflow and other sources for discussion and example code.

You need to collect the results of your stream work into another list. By the way, use meaningful names — I changed your list for the more descriptive name odds.

List < Integer > oddsSorted  = odds.stream().sorted().toList() ;

We can use streams to filter out the even numbers. The Arrays.stream method returns an IntStream.

The following code is untested, but should be close to correct.

int[] integerInputs= {1,3,4,6,9,7,8,2} ;
List < Integer > oddsSorted =
    Arrays
    .toStream( integerInputs )
    .filter( 
       integer -> integer % 2 != 0
    )
    .sorted()
    .boxed()  // Convert from `int` primitives to `Integer` objects.
    .toList()
;

As commented, you can directly sort the original source list by merely calling List#sort.

odds.sort( Comparator.naturalOrder() ) ;

Or more briefly:

odds.sort() ;

As commented, if you are new to programming, you might want to postpone your study of streams. Focus first on the conventional loops.

CodePudding user response:

The public static void main method does not call the method sortArray at all. It just loops through the array, and prints the values in the array. So, it just prints the numbers 1,3,4,6,9,7,8,2 as-is in the same order.

And the problem statement

to sort odd numbers in an ascending array

Does not exactly explain what needs to be done. So, should the odd numbers of an array be moved to the beginning of the array and all those in ascending order, while the even numbers should be pushed towards the end of the array? So the whole array won't be sorted, but all the odd numbers will be in ascending order and at the beginning of the array.

Also, even if the sortArray method is called, after sorting, it still prints the wrong result:

7
7
4
6
7
7
8
2

So, the logic is also wrong.

CodePudding user response:

Option 1: with Stream API

int filteredSortedArray[] = Arrays.stream(yourArray).filter(x -> x % 2 != 0).sorted().toArray();

Option 2:

  1. Use Arrays.sort(arr); to actually sort the array.

  2. Implement your filter logic in a loop and save the values to a new array

  3. Shorten the filtered array to the number of filtered values with Arrays.copyOf(filteredSortedArray, <new_array_length>);

    private int[] sortFilterOddArray(int[] arr) {
        Arrays.sort(arr);
    
        int[] filteredSortedArray = new int[arr.length];
        int counter = 0;
        for (int i : arr) {
            if (i % 2 == 0) continue;
            filteredSortedArray[counter] = i;
            counter  ;
        }
        return Arrays.copyOf(filteredSortedArray, counter);
    }
    
  •  Tags:  
  • java
  • Related