简体   繁体   English

使用 ListIterator 编写插入排序

[英]Writing Insertion Sort with ListIterator

I am trying to write an insertion sort method that takes in a list of Integers and sorts it in increasing order by using ListIterator.我正在尝试编写一个插入排序方法,该方法接受一个整数列表并使用 ListIterator 按升序对其进行排序。 I tried running the method on my main method to see if it has worked but, I end up with a bunch of errors.我尝试在我的主要方法上运行该方法以查看它是否有效,但是我最终遇到了一堆错误。 I would like to know what mistakes I have made and how you would write the code.我想知道我犯了哪些错误以及您将如何编写代码。 Here is the method:这是方法:

public static void insertionsort(LinkedList<Integer> arr){
ListIterator<Integer> it = arr.listIterator();
while(it.hasNext()){
  while(it.hasPrevious()){
    Integer curr = it.next();
    it.previous();
    Integer prev = it.previous();
    if(curr<prev){
      it.set(curr);
      it.next();
      it.next();
      it.set(prev);
    }
  }
  it.next();
}

} }

Here is the main method:下面是主要方法:

public static void main(String[] args){
LinkedList<Integer> a = new LinkedList<Integer>();
a.add(40);
a.add(30);
a.add(20);
a.add(10);
a.add(5);
insertionsort(a);
ListIterator<Integer> i = a.listIterator();
while(i.hasNext()){
  System.out.println(i.next());
}

} }

When this condition当这种情况

curr<prev

is not met you go into an infinite loop because you are leaving the cursor at the same place .没有遇到您 go 进入无限循环,因为您将 cursor 留在同一个地方

You could do something like this although not very efficient (but still insertion sort), but very easy to understand:你可以做这样的事情,虽然效率不高(但仍然是插入排序),但很容易理解:

    ListIterator<Integer> iter = arr.listIterator();
    Integer current = iter.next();
    Integer next = null;
    while (iter.hasNext()) {
        if (!iter.hasPrevious() && next != null) {
            //insertion into sorted sublist
            while (iter.hasNext() && iter.next() < next) ;
            iter.previous();
            iter.add(next);
        }
        next = iter.next();
        //nothing to do, keep going
        if (next >= current) {
            current = next;
        } else {
            //remove misplaced element, and check where to put it
            iter.remove();
            //we can go backwards and check or move to the beginning and keep checking
            iter = arr.listIterator();
            current = next;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM