繁体   English   中英

如何将元素从文件中递归插入数组? -java-

[英]How to insert elements from a file to an array recursively? -java-

我已经尝试了好一阵子了,但真的找不到解决方案。 我需要做的是将文件中的元素递归插入数组。 我意识到,只需循环就可以轻松完成此操作,但是由于这是家庭作业,因此必须递归完成。 我只想向正确的方向暗示。 我在理解递归时遇到很多麻烦,因此任何帮助都将是不错的。 真正令我困惑的部分是如何实际将元素放入数组中。 这是我到目前为止的内容:

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


public class Recursion{

 public static void main(String[]args) throws FileNotFoundException{

  int i= 0;
  int findInts = 0;
 // reading file
  Scanner scan = new Scanner(new File("heap.dat"));
  // finding ints in file
   while(scan.hasNextInt()){
      findInts = scan.nextInt();
       array(findInts);

  }

 }

 public static void array (int findInts) throws FileNotFoundException{
  int[] numbers = new int[1000]; // my array must have 1000 elements

   if(findInts == 0){
   System.out.println();
   }
   else{
   // Im really not sure what to do here
   // this gives me the infinite recursion error
   array(findInts);

   }


 }

任何递归解决方案都需要一个基本案例来决定何时终止递归。 如果缺少它,您将获得无限递归。 这是一个与您的情况有关的示例:

void addToArray(Scanner scan, int[] numbers, int index){
    if (scan.hasNextInt()){
        addToArray(scan, numbers, index++); //recursive case
    } else {
        return; //stop recursion
    }
}

注意,我故意省略了需要将数字添加到数组的部分。 由于这是一项家庭作业,因此我会让您知道;)

首先,尝试为您的递归方法命名“数组”以外的名称。 函数应提示其作用。 在这种情况下,“ recursiveInsert”是一个不错的选择。 另外,在方法外声明数组。

我还要补充一点,递归有一个“基本情况”,您可以在其中实际执行一个操作(返回一个值,或者在这种情况下插入一个新的数字),还有一个“归纳步骤”,在其中您可以使用新的参数再次调用该函数(请记住,必须始终使用相同的类型。

就您的情况而言,您似乎将拥有一个已排序的数组。 您需要一个算法以按顺序插入这些元素。 算法只是解决问题的一种方法。

这是一个建议的算法(它将以log(N)的顺序快速运行):查找“二进制搜索” BINARY SEARCH基本上,您检查列表的中间(长度/ 2)。 如果较大,请再次检查列表的下半部分,并限制开始和结束索引,如果较小则检查上半部分。

你将不得不改变你的方法的签名采取在开始和结束索引。

这是一些入门的代码...

 import java.util.*; import java.io.*; public class Recursion{ public static void main(String[]args) throws FileNotFoundException{ int i= 0; int findInts = 0; int [] array = new int[1000]//DECALRE YOUR ARRAY OUTSIDE METHOD // reading file Scanner scan = new Scanner(new File("heap.dat")); // finding ints in file while(scan.hasNextInt()){ findInts = scan.nextInt(); Recursive(findInts, 0, 1000, array); } } //insertMe is the num to insert, start and end are the indices //note that the array is passed to the method public static void recursiveInsert(int insertMe, int start, int end, int[] array) throws FileNotFoundException{ //BASE CASE if(start <= end - 1) { //insert the value at the index by copying the lower and upper halves into other arrays //and "move" the upper values over to make space. } //check the index to see if it fits if(array[end / 2] > InsertMe) { //check the middle point recursiveInsert(insertMe, start, end / 2, array); //result is that the middle point was greater } //so, recursively try again in lower-half //DO OTHER CODE THINGS HERE } 

暂无
暂无

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

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