Home > Blockchain >  Remove two items from the list so that it appears ordered
Remove two items from the list so that it appears ordered

Time:04-14

I have made it so that I get the elements that cause the list to be unordered. But how to delete them, and then display the list without them?

public class Main16 {
public static void main(String[] args){

    int arr[] = { 1, 2, 3, 7, 4, 5, 9, 6};
    int n = arr.length;

    printElements(arr, n);
}
static void printElements(int arr[], int n)
{

    for (int i = 1; i < n - 1; i  )
    {
        if (arr[i] > arr[i   1])
            System.out.print(arr[i]   " ");
    }
}

}

CodePudding user response:

This is definitely not the best way to sort arrays. The most optimized way to sort would be to convert your array to a Collection and use Collections.sort.

However - tried the below, using ArrayList to store the values to keep. (Also note, comparing as arr[i] > arr[i 1] will exclude the last element ∴ added a dummy value.)

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

public class Trial {

public static void main(String[] args) {

    int arr[] = {1,2,3,7,4,5,9,6};
    int n = arr.length;

    int newarr[] = new int[n   1];
    for (int i = 0; i < n; i  )
        newarr[i] = arr[i];

    newarr[n] = 1948; //Dummy Value Appended

    printElements(newarr, n   1);
}

static void printElements(int arr[], int n) {
    //Define an ArrayList to store the values that would not be removed
    List < Integer > valuesToKeep = new ArrayList < Integer > (Arrays.asList());
    for (int i = 0; i < n - 1; i  ) {
        if (arr[i] > arr[i   1]) {
            System.out.print("Removing item: "   arr[i]   "\n");

        } else {
            System.out.print("Keeping item: "   arr[i]   "\n");
            valuesToKeep.add(arr[i]); //Add
        }
    }
    Object[] valuesToKeep_array = valuesToKeep.toArray();

    //Print
    System.out.print("\nFinal Sorted Array: ");
    for (int i = 0; i < valuesToKeep_array.length; i  ) {
        System.out.print(valuesToKeep_array[i]);
    }
}}

CodePudding user response:

As Nexevis said, you can't really do what you want to do with arrays. You have 2 options:

  1. Go through the process of working with arrays and copying and transferring.

    1.5) You can also use java.util.Arrays.sort() if you just want an array that's in the right order, but it seems like you want to remove them outright:

Arrays.sort(arr);
  1. Use a List<Integer> because all you have to do is find the incorrect terms and then remove() them from the list. The length will automatically adjust. (I'd be happy to demonstrate how you'd do this if you want)
  • Related