【发布时间】:2014-05-30 12:54:32
【问题描述】:
我正在尝试创建名为 split 的方法,该方法根据键将列表分成 2 个列表。如果 list_1 和 list_2 是结果列表,则 list_1 应包含原始列表中键小于或等于传递的键的所有项,而 list_2 应包含原始列表中键大于传递的键的所有项。到目前为止,我将发布我的代码以及其他人的建议
public class UnorderedArrayList extends ArrayListClass {
public UnorderedArrayList() {
super();
}
public UnorderedArrayList(int size) {
super(size);
}
//Bubble Sort
public void bubbleSort() {
for (int pass = 0; pass < length - 1; pass++) {
for (int i = 0; i < length - 1; i++) {
if (list[i] > list[i + 1]) {
int temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
}
}
}
}
//implementation for abstract methods defined in ArrayListClass
//unordered list --> linear search
public int search(int searchItem) {
for(int i = 0; i < length; i++)
if(list[i] == searchItem)
return i;
return -1;
}
public void insertAt(int location, int insertItem) {
if (location < 0 || location >= maxSize)
System.err.println("The position of the item to be inserted is out of range.");
else if (length >= maxSize)
System.err.println("Cannot insert in a full list.");
else {
for (int i = length; i > location; i--)
list[i] = list[i - 1]; //shift right
list[location] = insertItem;
length++;
}
}
public void insertEnd(int insertItem) {
if (length >= maxSize)
System.err.println("Cannot insert in a full list.");
else {
list[length] = insertItem;
length++;
}
}
public void replaceAt(int location, int repItem) {
if (location < 0 || location >= length)
System.err.println("The location of the item to be replaced is out of range.");
else
list[location] = repItem;
}
public void remove(int removeItem) {
int i;
if (length == 0)
System.err.println("Cannot delete from an empty list.");
else {
i = search(removeItem);
if (i != -1)
removeAt(i);
else
System.out.println("Cannot delete! The item to be deleted is not in the list.");
}
}
public void merge(UnorderedArrayList list2,UnorderedArrayList list1){
int num=0;
for(int j=0; j<list1.length;j++){
num= list1.retrieveAt(j);
insertEnd(num);
}
for(int i=0; i<list2.length-1;i++){
num=list2.retrieveAt(i);
insertEnd(num);
}
}
public void split(UnorderedArrayList list2, UnorderedArrayList list1, UnorderedArrayList list, int item){
int listItem = item;
while(!list.isEmpty()){
list.retrieveAt(listItem);
if(listItem>item){
if(!list2.isFull()){
list2.insertAt(listItem);
}
}
}
}
//what i got so far from the internet
/* void UnsortedType::SplitLists(ItemType item, UnsortedType& list1, UnsortedType& list2){
ItemType listItem;
list.ResetList();
while ( !list.IsLastItem()) {
list.GetNextItem(listItem);
if(listItem > item) {
if (!list2.IsFull())
list2.InsertItem(listItem);
}
else {
if ( !list1.IsFull())
list1.InsertItem(listItem);
} }}
*/
【问题讨论】:
-
到底是什么问题?无论如何,您的方法有一个
list1参数,但似乎忽略了它。 -
你要找的这个实现其实是定义为
Quicksort的分区方式。有数百甚至数千个代码示例。