gpt4 book ai didi

Java - 合并排序数组

转载 作者:行者123 更新时间:2023-12-02 05:02:34 25 4
gpt4 key购买 nike

我正在为一家商店制定算法。我制作了一个包含客户信息的数组。现在我想对此数组实现合并排序并按年龄对其进行排序。这是我的客户类别代码:

public class Customer{

private int customerID;
private String name;
private int age;
private char gender;
private String email;

public List<Customer> customerList = new ArrayList<Customer>();

public Customer(String name, int age, char gender, String email) {
this.customerID = customerList.size();
this.name= name;
this.age= age;
this.gender= gender;
this.email = email;
customerList.add(this);
}
public int getCustomerID() {
return customerID;
}

public void setCustomerID(int customerID) {
this.customerID = customerID;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name= name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public char getGender() {
return gender;
}

public void setGender(char gender) {
this.gender = gender;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

}

这是我的合并排序:

    private int[] helper;
private int number;

public void sort(Klant[] values) {
this.customerList= values; <---Error
number = values.length;
this.helper = new int[number];
mergesort(0, number - 1);
}

private void mergesort(int low, int high) {
// check if low is smaller then high, if not then the array is sorted
if (low < high) {
// Get the index of the element which is in the middle
int middle = low + (high - low) / 2;
// Sort the left side of the array
mergesort(low, middle);
// Sort the right side of the array
mergesort(middle + 1, high);
// Combine them both
merge(low, middle, high);
}
}

private void merge(int low, int middle, int high) {

// Copy both parts into the helper array
for (int i = low; i <= high; i++) {
helper[i] = customerList[i];
}

int i = low;
int j = middle + 1;
int k = low;
// Copy the smallest values from either the left or the right side back
// to the original array
while (i <= middle && j <= high) {
if (helper[i] <= helper[j]) {
customerList[k] = helper[i];
i++;
} else {
customerList[k] = helper[j];
j++;
}
k++;
}
// Copy the rest of the left side of the array into the target array
while (i <= middle) {
customerList[k] = helper[i];
k++;
i++;
}

}

上线:this.customerList = 值;我收到错误:不兼容的类型 Customer[] 无法转换为 List

我的问题是如何修复此错误以及我的合并排序是否正确?

编辑1:@詹斯您的第一个选择: this.customerList= Arrays.asList(values);

修复了错误。但现在我在这一行遇到错误:

            helper[i] = customerList[i];

它说:需要数组,但找到了列表

有人知道如何解决这个问题吗?

最佳答案

您不能将数组分配给列表。

尝试

 this.customerList= Arrays.asList(values);   

或者将方法参数更改为 List<Customer>

public void sort(List<Customer> values) {

关于Java - 合并排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28117727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com