Как создать массив из содержимого текстового файла для сортировки? - PullRequest
0 голосов
/ 16 сентября 2018

Это программа, которая берет эти три массива и сортирует их, используя сортировку вставками и подсчитывая количество сравнений и обменов, выполненных для каждого массива при сортировке.

Сейчас я пытаюсь протестировать три других массива, которые были созданы для текстовых файлов. Эти три текстовых файла являются просто списками чисел, первый текстовый файл называется «array4.txt», и его список чисел содержит от 1 до 2000 по порядку.

Второй файл называется "array5.txt", и его список чисел содержит от 2000 до 1 в порядке убывания. Наконец, третий файл называется «array6.txt», и его список чисел содержит список случайно смешанных чисел от 1 до 2000, включая 1 и 2000 без повторов.

Моя цель - прочитать эти файлы и поместить их значения в фактический массив, а мой метод сортировки вставками - прочитать их, отсортировать их и посчитать количество сравнений и обменов так же, как я делал с моими первыми тремя массивами.

Я очень новичок в Java и не знаю точно, как это сделать.

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

public class InsertionSort
{
    public static void main(String args[]) throws IOException
    {    
    int[] Array  = {1,2,3,4,5,6,7,8,9,10};  
    int[] Array2 = {10,9,8,7,6,5,4,3,2,1};
    int[] Array3 = {1,10,2,9,3,8,4,7,5,6};

    System.out.println("Insertion Sort: ");
    System.out.println();
    System.out.println("Best Case Scenario: ");
    printArray(Array);
    insertionSort(Array);

    System.out.println("Worst Case Scenario: ");

    printArray(Array2);

    insertionSort(Array2);

    System.out.println("Average Case Scenario: ");
    printArray(Array3);
    insertionSort(Array3);
}

public static void insertionSort(int[] list) 
{
    int comps = 0, swaps = 0;

    for(int i = 1; i < list .length; i++) {

        int j = i;      

        // compare i with sorted elements and insert it
        // sorted elements: [0..i-1]
        while (j > 0 && list[j] < list[j - 1]) {

            int temp = list[j];
            list[j] = list[j - 1];
            list[j - 1] = temp;

            swaps++;
            comps++;  // loop condition true

            j--;
        }
        comps++; // checking loop condition when false
    }
    //printArray(list);

    System.out.println("Comparisons: " + comps 
        + " Swaps: " + swaps);
    System.out.println();
}

static void printArray(int[] array){

    for(int i=0; i < array.length; i++)
    {  
        System.out.print(array[i] + " ");
    } 
    System.out.println();

}

}

Ответы [ 2 ]

0 голосов
/ 16 сентября 2018

Это то, что я придумал.Надеюсь, поможет!

package com.company;

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        // Replace array.txt with the name of your txt file and your path
        Scanner fileScanner = new Scanner(new File("array.txt"));
        // Counter variable so we'll know the size of the array we'll need
        int counter = 0;
        // Iterate through the file counting the number of integers and incrementing the counter variable
        while(fileScanner.hasNextInt()){
            counter++;
            fileScanner.nextInt();
        }
        // Reset the scanner to the beginning of the txt file
        fileScanner = new Scanner(new File("array.txt"));

        // Scan each integer into the array
        int [] array = new int[counter];
        for (int i = 0; i < array.length; ++i) array[i] = fileScanner.nextInt();
    }
}
0 голосов
/ 16 сентября 2018

Вот, пожалуйста:

public void getIt() {
    List<Integer> ints = new ArrayList(); //temporary holder

    try (Scanner scanner = new Scanner("filename.txt")) { //open a scanner that will scan our file
        scanner.forEachRemaining(line -> { //iterate through each line in our file
            String[] numberStrings = line.split(","); // the comma is your presumed delimeter IF one exists
            for (int x = 0; x < numberStrings.length; x++) { // loop through each item separated by a comma on each line
                ints.add(Integer.parseInt(numberStrings[x])); // turn this string into an int and add it to your list
            }
        });
    }
    Integer[] integerArray = ints.toArray(new Integer[ints.size()]); //transform our list into an array
}

Если это только одно число в строке, вам не нужен цикл for или line.split внутри forEachRemaining

...