2012-04-17 2 views
0

Хорошо, моя цель - сортировать текстовый файл с одной строкой в ​​строке. Я придерживался той точки, где мне нужно создать класс Insertion. Как передать единственный список ссылок (моя собственная реализация, а не Java) и что еще мне нужно передать в качестве параметра? Вот мой код. P.S Причина, по которой я использую свою собственную реализацию связанного списка, заключается в том, что я хочу знать, как это работает и как работают различные действия с использованием связанного списка.Как реализовать сортировку вставки?

Любая помощь была бы принята с благодарностью.

Главное:

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")) ; 
    } 
} 

Реализация списка:

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() ; 
     } 
    } 
} 

Записи (ссылки) Создатель:

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("") ; 
    } 
} 

И всемогущий класс Вставка рода:

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

    } 
} 
+1

Вы должны изменить название «Как реализовать сортировку вставки в Java?» :) Попробуйте следующую ссылку http://www.roseindia.net/java/beginners/arrayexamples/InsertionSort.shtml –

+0

Как именно я должен изменить это, чтобы сортировать строку? – serge

ответ

1

Это сообщение, по-видимому, задает два отдельных вопроса. Поэтому я ответил им отдельно.

EDIT: Просто заметили проблему с вашим классом связанных списков. Вы должны сначала исправить это, а затем взглянуть на мои ответы на ваши вопросы.

Ваша реализация неверна, потому что вы не храните ссылку на следующую ссылку в связанном списке. Entries должен хранить ссылку на следующий элемент. Я рекомендую читать this article.

Если вы посмотрите на диаграмму на этой странице ...

Singly linked list

каждое звено (или запись, как вы вызываете его) имеет ссылку, указывающую на его соседа.

Реализация Вносимые рода

Я предполагаю, что вы хотите отсортировать вы связанный список в алфавитном порядке по записи внутри него. Если это так, вы просто меняете целочисленное сравнение в сортировках вставки, которое вы увидите в текстовых книгах/в Интернете для алфавитного сравнения.

Взгляните на Comparing strings by their alphabetical order. Это аналогичный вопрос, который рассказывает вам, как делать алфавитные сравнения.

Я также написал класс сортировки вставки в Scala для целых чисел прошлой ночью here вам может показаться полезной.

Перебор LinkedList

Для прохождения вашего связанного списка вы просто передать head ссылку. вы можете выполнить итерацию через связанный список, вызвав элемент next списка.

например ..

while(link < null){ 
    link.next 
} 

Предполагая link равно главе списка выше цикл будет продолжаться, чтобы получить следующий элемент в связанном списке на до нулевого (который должен представлять конец списка)

+0

ok Спасибо, дайте мне время, чтобы разобраться и отправить обратно – serge

+0

только что закончил первую часть (ссылка). похоже ли это нормально? – serge

+0

@ voth1234 Да, это кажется правильным. Лучшим способом тестирования этого было бы создание функции 'insert()', которая позволяет вставлять ссылку, вставлять 6 или 7 из них, а затем пересекать их, используя цикл while, который я предоставил в своем коде. Это позволит вам увидеть, что связанный список был создан. – Aidanc

Смежные вопросы