Home > database >  How can I insert elements to the array alphabetically?
How can I insert elements to the array alphabetically?

Time:09-29

I have a data structure. It is working with array and I want to insert elements to the array alphabetically. I did this but it doesnt work. It is in sortedInsert method. I cut out where the other methods are. How can I do it?

    private Product[] arr;
    private int size;
    private int sortCost;
    public ProductArray(int len) {
        arr = new Product[len];
        size = 0;
    }
    
     void sortedInsert(Product pr) {
         for(int i = 0; i < size ; i  ) {
             if(arr[i].getName().compareTo(pr.getName()) < 0) {
                 size  ;
                 for(int j = i; j < size; j  ) {
                     
                     arr[j 1] = arr[j];
                     
                 }
                 arr[i] = pr;
                 
             }
         }
     } 
    
    
} ```

And this is my Product class: :


class Product {
    private String name;
    private String description;
    private int price;
    public Product(String name_, String description_, int price_) {
            // constructor
            name = name_;
            description = description_;
            price = price_;
        }
public void displayProduct() {
            System.out.print(" Product name: "   name);
            System.out.print(", Description: "   description);
            System.out.println(", Price: "   price);
        }
public String getName(){
            return name;
}
}

CodePudding user response:

This is an Array and static in size. in order to do what you are trying you will have to allocate a new array, with a length of oldLength 1. Then you can search for the first element (n) which is alphabetically located after the new element and System.arraycopy all elements before n, then insert the new one and then arraycopy all elements from (n) to the end of the array.

CodePudding user response:

As a previous answer mentioned, an array in Java has a fixed size, so you would need to re-allocate the array to make room for a new element.

Probably the easiest answer here is to use one of Java's Collection classes which provide automatic reallocation instead, like an ArrayList (add an element, then sort the list with Collections.sort()), or maybe a TreeSet (which would automatically maintain proper sort order when you add an item)

CodePudding user response:

First the solution with what we have:

void sortedInsert(Product product) {
    int index = Arrays.binarySearch(arr, 0, size, product,
                    Comparator.comparing(Product::getName));
    if (index >= 0) { // Found
        System.out.println("There already exists a product with that name");
        arr[index] = product;
    } else { // Not found, ~(insert_position);
        index = ~index;
        System.arraycopy(arr, index, arr, index   1, size - index);
        // Shifts to the right.
          size;
        arr[index] = product;
    }
}

There is a usefull binary search returning the position of the found one, or ~position (= -position - 1; < 0) for the insert position.

System.arraycopy is an old copying of an array slice.

A lambda (anonymous function) is used to get then name gettter - for comparison.

Better would be to have a Map from name to Product. SortedMap's exist, like a TreeMap.

private final SortedMap<String, Product> allProductsByName =
        new TreeMap<>(Comparator.comparing(Product::getName));

Product anyOldPr = allProductsByName.put(pr.getName(), pr);
if (anyOldPr != null) oops;
  •  Tags:  
  • java
  • Related