【问题标题】:Implementing insertion sort, passing list to other class?实现插入排序,将列表传递给其他类?
【发布时间】:2012-04-29 13:50:45
【问题描述】:

我昨天发布了代码的一个版本,但我认为它可以处理一些改进或什么。事情是我再次卡住了。如您所见,我正在尝试对链表进行排序并将其写回文本文件。第一个问题是,在 Insertion 类中传递什么以及如何传递?第二个问题是如何按字母顺序实现插入排序?我已经看到了许多使用整数和数组进行插入的示例,但我似乎仍然遇到了麻烦。这是我到目前为止的进展。

编辑 1:忘记那个。

编辑 2:如何使用我的方法实现 Comparable 并使用字母排序 (CompareToIgnoreCase)?

主要:

import java.io.* ;
import java.util.Scanner ;

public class Sort 
{
    public static void main(String[] args) throws Exception 
    {
        File outputFile ;
        Scanner kb = new Scanner (System.in) ; 
        LinkedList list = new LinkedList() ;
        String command ;
        Insertion insertion = new Insertion() ;

        // Create the new text file. If exists, it will continue to the next commands
        do
        {
            outputFile = new File("db.txt") ;

                if(!outputFile.exists())
                {
                    outputFile.createNewFile ();                    
                    System.out.println("The file was created as db.txt");
                    System.out.println("");
                }

        }while (!outputFile.exists()) ;

        // Define which file to stream in from          
        FileInputStream fileIn = new FileInputStream("db.txt") ;
        DataInputStream input = new DataInputStream (fileIn) ;
        BufferedReader br = new BufferedReader (new InputStreamReader (input)) ;
        String line ;

        try
        {               
            // Read each line of the file               
            while ((line = br.readLine()) != null)
            {
                list.add(line) ;
            }       
            input.close() ;
        }catch (Exception e){
            System.err.println("Error. Could not read the file") ;
        }

        //System.out.println (list.toString()) ;

        //Welcome message
        System.out.println("Welcome. \nPlease use the following commands [-i for Insertion Sort, -s for Selection Sort, -m for Merge sort, Exit to terminate]: " );
        System. out.println ("") ;          
        command = kb.next() ;

        do
        {
            if (command.equalsIgnoreCase("-i"))
            {
                insertion.Sort(list, list.size()) ;

                //try
                //{
                    //the "true" argument sets the FileWriter to append mode so that is does not overwrite the first line
                //  BufferedWriter out = new BufferedWriter(new FileWriter("db.txt", true));
                    //out.write(textContent) ;
                    //out.newLine() ;
                    //out.close() ;
                //}catch(IOException e)
                //{
                //  System.out.println("Could not write to file") ;
                //  System.exit(0) ;
                //}

                //System.out.println ("Enter command:") ;
                //command = kb.next() ;

            }

            else if (command.equalsIgnoreCase("-s"))
            {

            }
            else if (command.equalsIgnoreCase("-m"))
            {

            }
            else if (command.equalsIgnoreCase("Exit"))
            {
                System.exit(0) ;
            }
            else 
            {
                System.out.println("Unknown command. Please use -i, -s, -m or EXIT") ;
                command = kb.next() ;
            }
        }while (!command.equalsIgnoreCase("Exit")) ;

    }
}

链表:

    import java.lang.* ;

public class LinkedList
{
    //reference to the head node
    public Node head ;
    public int listCount ;

    //LinkedList Constructor
    public LinkedList ()
    {
        //empty list
        head = new Node (null) ;
        listCount = 0 ;
    }

    //add element to the end of the list
    public void add(String data)
    {
        Node temp = new Node (data) ;
        Node current = head ;

        //go to the end of the list
        while (current.getNext() != null)
        {
            current = current.getNext() ;
        }

        // last node\s next reference is set to the last node
        current.setNext(temp) ;
        //increment the number of elements
        listCount++ ; 
    }

    //return the size of the list
    public int size()
    {
        return listCount ;
    }

    public String toString()
    {
        Node current = head.getNext() ;
        String output = " " ;
        while (current != null)
        {
            output += "[" + current.getData().toString() + "]" ;
            current = current.getNext() ;
        }
        return output ;
    }


}

插入:

public class Insertion 
{
    public static void Sort (LinkedList listIn, int size)
    {
        int temp, i, j ;
        for (j=1;j<size;j++)
        {
            while(listIn.head)
        }
    }
}

节点类:

    public class Node 
    {
        //reference to the next node or null if not any
        Node next ;
        //the entries
        String data ;

        //Node Constructor
        public Node (String dataIn)
        {
            next = null ;
            data = dataIn ;
        }

        //Node constructor in case of the need to point to a certain node
        public Node (String dataIn, Node nextIn)
        {
            next = nextIn;
            data = dataIn ;
        }

        public String getData ()
        {
            return data ;
        }

        public void setData (String dataIn)
        {
            data = dataIn ;
        }

        public Node getNext ()
        {
            return next ;
        }

        public void setNext (Node nextIn)
        {
            next = nextIn ;
        }
    }
}

【问题讨论】:

    标签: java list linked-list insertion


    【解决方案1】:

    什么以及如何传入 Insertion 类?

    你是说方法吗?您应该(至少)传入完整的LinkedList(而不仅仅是头部Node)。

    第二个问题是如何按字母顺序实现插入排序?

    要么获取类型实现Comparable 的元素列表,要么获取单独的Comparator 参数,并使用它来比较元素。然后你可以传入一个StringComparator 以获得Strings 的列表,一个IntComparator 用于Integers 等。你所需要的只是实现所需的比较器,这通常是微不足道的,因此你可以重用你的任何类型的排序算法。

    第一种方法更简单,它直接适用于Strings(因为String 已经实现了Comparable)。但是请注意,它仅限于对象类型 - 对于 int 等原始类型,您需要第二种方法。再说一次,你不能让泛型集合存储原始类型的元素。

    您可以在Collections 中查看两种泛型sort 方法的示例:

    public static <T extends Comparable<? super T>> void sort(List<T> list);
    public static <T> void sort(List<T> list, Comparator<? super T> c)
    

    如果你想保留你的 LinkedList 非泛型,你可以删除(大部分)泛型绒毛:

    public static void sort(LinkedList list);
    public static void sort(LinkedList list, Comparator<? super String> c)
    

    【讨论】:

    • 有什么方法可以让我不必使用现成的 java 类?无论如何,这不是家庭作业,它只是我更好地学习 java 的一种方式。
    • @voth1234,您不必这样做 - Comparator 是一个您可以按照自己的方式实现的接口。 sort 方法仅作为正确方法签名的示例显示 - 随意实现您自己的,但是最好从一开始就学习有关 API 等的最佳实践和约定。此外,在您完成自己的实现之后,甚至可以深入了解Collections.sort 方法的实现,看看它们的不同之处,然后找出原因。
    • 我会努力的,谢谢。看看我上面的排序方法。我通过了列表并打印了它(这可能意味着它正确地通过了)但它不会停止打印,它陷入了无限循环。我没有看到问题。有什么想法吗?
    • 我没有看到任何明显的错误。尝试添加一个迭代列表的方法,方法与toString 相同,但不是将节点数据附加到本地String,而是直接将其打印到屏幕上。然后将该方法的输出与列表的预期内容进行比较——这可能会给你一个线索。
    • 问题。从上面的代码中究竟需要实现哪些可比性?我也尝试按照您所说的直接打印,但失败了:)。有什么办法可以将排序方法中传递的列表写入文本文件?
    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多