简体   繁体   English

如何实现插入排序?

[英]How to implement Insertion Sort?

Ok, my goal is to be able to sort a text file of single entry per line. 好的,我的目标是能够对每行单个条目的文本文件进行排序。 Im stuck to the point where i have to create the Insertion class. 我陷入了必须创建插入类的地步。 How do i pass the single link list (my own implementation, not Java's) and what else do i need to pass as a parameter? 如何传递单个链接列表(我自己的实现,而不是Java的实现),还有什么需要作为参数传递的? Here's my code so far. 到目前为止,这是我的代码。 PS The reason im using my own implementation of the linked list is because i want to know how the thing works and how the various actions done using a linked list work. PS我使用自己的链表实现是因为我想知道它是如何工作的以及使用链表进行的各种动作是如何工作的。

Any help would be greatly appreciated. 任何帮助将不胜感激。

The Main: 主要的:

    import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;


public class Sort
{
    public static void main(String[] args) throws Exception
    {
        Scanner kb = new Scanner (System.in) ;
        File outputFile ;
        EntriesList list = new EntriesList () ;
        String line ;
        String entry ;
        String command ;
        String textContent ;


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

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

        }while (!outputFile.exists()) ;

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

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

        //Welcome message + entry counter
        System.out.println("Welcome. \nYou about to sort " + list.count("Entries.txt") + " entries. \nPlease use the following commands [Add -add new entry, View -view entries before sorting, -i -Insertion Sort, -s -Selection Sort, -m -Merge Sort, Exit]: " );
        System. out.println ("") ;          
        command = kb.next() ;

        // User Input
        do
        {
            if (command.equalsIgnoreCase("Add"))
            {
                System.out.println("Enter String value:") ;
                entry = kb.next() ;
                textContent = entry ;
                System.out.println("Entry added successfully") ;

                try
                {
                    //the "true" argument sets the FileWriter to append mode so that is does not overwrite the first time
                    BufferedWriter out = new BufferedWriter(new FileWriter("Entries.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() ;

                list.insert(entry) ;
            }

            else if (command.equalsIgnoreCase("View"))
            {
                if (!list.isEmpty())
                {
                    list.printList();
                    System.out.println ("Enter command:") ;
                    command = kb.next() ;
                }
                else
                {
                    System.out.println("File is empty. Please enter records first.");
                    System.out.println ("Enter ADD command:") ;
                    command = kb.next();
                }
            }
            else if (command.equalsIgnoreCase("Exit"))
            {
                System.exit(0) ;
            }
            else 
            {
                System.out.println("Unknown command. Please use ADD, VIEW or EXIT") ;
                command = kb.next() ;
            }
        }while (!command.equalsIgnoreCase("Exit")) ;
    }
}

The List implementation: List实现:

    import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


public class EntriesList 
{
    private Entries head;
    private int listCount ;

    //LinkList constructor
    public EntriesList()
    {
            head = new Entries (null) ;
            listCount = 0 ;            
    }

    //Returns true if list is empty
    public boolean isEmpty() 
    {
            return head == null;
    }

    //Inserts a new Entry at the end of the list
    public void insert(String entryIn) 
    {
            Entries temp = new Entries (entryIn) ;
            Entries current = head ;

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

            // Last Entries's next reference is set to the noew node 
            current.setNext(temp) ;
            listCount++ ;
    }

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

        //Prints list data
    public void printList()
    {
            Entries currentEntry = head;
            while(currentEntry != null)
            {
                currentEntry.printLink();
                currentEntry = currentEntry.nextEntry;
            }
            System.out.println("");
    }

 // Count the lines in the text file
    public int count(String filename) throws IOException 
    {
        InputStream is = new BufferedInputStream(new FileInputStream(filename));
        try 
        {
            byte[] c = new byte[1024] ;
            int count = 0 ;
            int readChars = 0 ;
            while ((readChars = is.read(c)) != -1) 
            {
                for (int i = 0 ; i < readChars ; ++i)
                {
                    if (c[i] == '\n')
                        ++count ;
                }
            }
            return count ;
        } finally
        {
            is.close() ;
        }
    }
}

The Entries (links) creator: 条目(链接)创建者:

public class Entries
{
    public String entry ;
    public Entries nextEntry;

    // Empty Link Constructor
    public Entries ()
    {

    }

    //Link constructor
    public Entries(String entryIn) 
    {
        entry = entryIn ;
        nextEntry = null ;
    }

    public String getEntry () 
    {
        return entry ;
    }

    public void setEntry (String entryIn)
    {
        entry = entryIn ;
    }

    public Entries getNext () 
    {
        return nextEntry ;
    }

    public void setNext (Entries nextEntryIn)
    {
        nextEntry = nextEntryIn ;
    }

    //Print Link data
    public void printLink()
    {
            System.out.println("") ;
            System.out.print(getEntry() +"\n");
            System.out.println("") ;
    }
}

And the almighty Insertion sort class: 和全能的插入排序类:

public class Insertion 
{
    public String Sort (EntriesList list)
    {

    }
}

This post appears to be asking two separate questions. 这篇文章似乎在问两个独立的问题。 So I've answered them separately. 所以我已经分别回答了。

EDIT: Just noticed a problem with your linkedlist class. 编辑:刚注意到您的链表类有问题。 You'll have to first fix this and then take a look at my answers to your questions. 您必须先解决此问题,然后查看我对问题的回答。

Your implementation is incorrect because you're not storing a reference to the next link in the linkedlist. 您的实现不正确,因为您没有在链表中存储对下一个链接的引用。 Entries should store a reference to the next element. Entries应存储对下一个元素的引用。 I recommend reading this article. 我建议阅读这篇文章。

If you look at the diagram on that page... 如果您查看该页面上的图表...

单链表

each link (or entry as you're calling it) has a link pointing to its neighbour. 每个链接(或您所称的条目)都有一个指向其邻居的链接。

Implementing Insertion sort 实现插入排序

I assume you want to sort you linked list alphabetically by the entry inside of it. 我假设您想按其内部的条目按字母顺序对链接列表进行排序。 If this is the case you simply swap out the integer compare in insertion sorts you'll see in text books / on the web for an alphabetical comparison. 如果是这种情况,您只需换掉插入比较中的整数比较,就可以在教科书/网络中看到该比较以进行字母比较。

Take a look at Comparing strings by their alphabetical order it's a similar question which tells you how to do alphabetical comparisons. 看看按字母顺序比较字符串,这是一个类似的问题,告诉您如何进行字母比较。

I also wrote a insertion sort class in Scala for integers last night here you might find it useful. 昨晚我还在Scala中为整数写了一个插入排序类,在这里您可能会发现它很有用。

Iterating over a LinkedList 遍历LinkedList

For passing your linked list you simply pass the head link. 要传递链接列表,您只需传递head链接。 you can then iterate through the linkedlist by calling the next element of the list. 然后您可以通过调用列表的next元素来遍历链表。

for example.. 例如..

while(link < null){
  link.next
}

Assuming link is equal to the head of the list the above loop will continue to get the next element in the linked list on till null (which should represent the end of the list) 假设link等于列表的开头,则上述循环将继续获取链表中的下一个元素,直到null(应该代表列表的末尾)为止。

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

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