如何按字母顺序插入元素到数组?



我有一个数据结构。它正在处理数组,我想按字母顺序向数组插入元素。我这样做了,但它不起作用。它在sortedInsert方法中。我把其他方法都剪掉了。我该怎么做呢?

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;
}
}

这是一个数组,大小是静态的。为了做你正在尝试你将不得不分配一个新的数组,与oldLength + 1的长度。然后,您可以搜索第一个元素(n),它按字母顺序位于新元素和System之后。

将n之前的所有元素Arraycopy,然后插入新的元素,然后将(n)开始的所有元素Arraycopy到数组末尾。

正如前面提到的,Java中的数组具有固定大小,因此您需要重新分配数组以为新元素腾出空间。

可能这里最简单的答案是使用Java的Collection类之一,它提供自动重新分配,而不是ArrayList(添加一个元素,然后用Collections.sort()对列表排序),或者TreeSet(当你添加一个项目时,它会自动保持适当的排序顺序)

首先是我们现有的解决方案:

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;
}
}

有一个有用的二进制搜索返回找到的位置,或者~position (= -position - 1;& lt;0)为插入位置。

System.arraycopy是数组切片的旧拷贝。

使用lambda(匿名函数)获取名称getter -以便比较。

最好有一个从名称到产品的映射。SortedMap的存在,就像TreeMap。

private final SortedMap<String, Product> allProductsByName =
new TreeMap<>(Comparator.comparing(Product::getName));
Product anyOldPr = allProductsByName.put(pr.getName(), pr);
if (anyOldPr != null) oops;

最新更新