segment tree correct but query output is not












0















I tried to implement segment tree algorithm for finding range minimum query in Java. Here is my complete java code. It builds the segment tree from an array. and then prints the minimum element in every range. the problem is, tree is correct (as far as I know), but the output is always the least element of whole array. :-| kindly point out where I am going wrong.



public class Solution {

static int arr = {-1, 2, 4, 0};
static int st;

public static void main(String args) {

st = new int [ 2 * arr.length-1];

buildTree(0, 0, arr.length-1);

System.out.print("original array: ");
showArray(arr);

System.out.print("segment tree: ");
// shows segment tree
showArray(st);

System.out.println("nqueries: n");

// prints minimum in every range
for(int i=0; i<arr.length; i++) {
for(int j=i+1; j<arr.length; j++)
System.out.println(i+":"+j+" -> "+search(i, j));
}

}

// builds segment tree
static void buildTree(int pos, int left, int right) {

if(left == right) {
st[pos] = arr[left];
return;
}

int mid = (left + right) / 2;

buildTree(left(pos), left, mid);
buildTree(right(pos), mid+1, right);

int p1 = left(pos);
int p2 = right(pos);

st[pos] = (st[p1] > st[p2]) ? st[p2] : st[p1];
}

// left child
static int left(int pos) {
return pos * 2 + 1;
}

// right child
static int right(int pos) {
return pos * 2 + 2;
}

static int search(int left, int right) {

return rmq(0, 0, st.length, left, right);
}

// range minimum query function
static int rmq(int pos, int left, int right, int qleft, int qright) {

if((qleft > right) && (qright < left))
return Integer.MAX_VALUE;

if((qleft <= left) || (qright >= right))
return st[pos];

int mid = (left + right) / 2;

int l = rmq(left(pos), left, mid, qleft, qright);
int r = rmq(right(pos), mid + 1, right, qleft, qright);

return (l > r) ? r : l;
}

// show segment tree
static void showArray(int arr) {

for(Integer x : arr)
System.out.print(x+" ");
System.out.println();
}
}









share|improve this question





























    0















    I tried to implement segment tree algorithm for finding range minimum query in Java. Here is my complete java code. It builds the segment tree from an array. and then prints the minimum element in every range. the problem is, tree is correct (as far as I know), but the output is always the least element of whole array. :-| kindly point out where I am going wrong.



    public class Solution {

    static int arr = {-1, 2, 4, 0};
    static int st;

    public static void main(String args) {

    st = new int [ 2 * arr.length-1];

    buildTree(0, 0, arr.length-1);

    System.out.print("original array: ");
    showArray(arr);

    System.out.print("segment tree: ");
    // shows segment tree
    showArray(st);

    System.out.println("nqueries: n");

    // prints minimum in every range
    for(int i=0; i<arr.length; i++) {
    for(int j=i+1; j<arr.length; j++)
    System.out.println(i+":"+j+" -> "+search(i, j));
    }

    }

    // builds segment tree
    static void buildTree(int pos, int left, int right) {

    if(left == right) {
    st[pos] = arr[left];
    return;
    }

    int mid = (left + right) / 2;

    buildTree(left(pos), left, mid);
    buildTree(right(pos), mid+1, right);

    int p1 = left(pos);
    int p2 = right(pos);

    st[pos] = (st[p1] > st[p2]) ? st[p2] : st[p1];
    }

    // left child
    static int left(int pos) {
    return pos * 2 + 1;
    }

    // right child
    static int right(int pos) {
    return pos * 2 + 2;
    }

    static int search(int left, int right) {

    return rmq(0, 0, st.length, left, right);
    }

    // range minimum query function
    static int rmq(int pos, int left, int right, int qleft, int qright) {

    if((qleft > right) && (qright < left))
    return Integer.MAX_VALUE;

    if((qleft <= left) || (qright >= right))
    return st[pos];

    int mid = (left + right) / 2;

    int l = rmq(left(pos), left, mid, qleft, qright);
    int r = rmq(right(pos), mid + 1, right, qleft, qright);

    return (l > r) ? r : l;
    }

    // show segment tree
    static void showArray(int arr) {

    for(Integer x : arr)
    System.out.print(x+" ");
    System.out.println();
    }
    }









    share|improve this question



























      0












      0








      0








      I tried to implement segment tree algorithm for finding range minimum query in Java. Here is my complete java code. It builds the segment tree from an array. and then prints the minimum element in every range. the problem is, tree is correct (as far as I know), but the output is always the least element of whole array. :-| kindly point out where I am going wrong.



      public class Solution {

      static int arr = {-1, 2, 4, 0};
      static int st;

      public static void main(String args) {

      st = new int [ 2 * arr.length-1];

      buildTree(0, 0, arr.length-1);

      System.out.print("original array: ");
      showArray(arr);

      System.out.print("segment tree: ");
      // shows segment tree
      showArray(st);

      System.out.println("nqueries: n");

      // prints minimum in every range
      for(int i=0; i<arr.length; i++) {
      for(int j=i+1; j<arr.length; j++)
      System.out.println(i+":"+j+" -> "+search(i, j));
      }

      }

      // builds segment tree
      static void buildTree(int pos, int left, int right) {

      if(left == right) {
      st[pos] = arr[left];
      return;
      }

      int mid = (left + right) / 2;

      buildTree(left(pos), left, mid);
      buildTree(right(pos), mid+1, right);

      int p1 = left(pos);
      int p2 = right(pos);

      st[pos] = (st[p1] > st[p2]) ? st[p2] : st[p1];
      }

      // left child
      static int left(int pos) {
      return pos * 2 + 1;
      }

      // right child
      static int right(int pos) {
      return pos * 2 + 2;
      }

      static int search(int left, int right) {

      return rmq(0, 0, st.length, left, right);
      }

      // range minimum query function
      static int rmq(int pos, int left, int right, int qleft, int qright) {

      if((qleft > right) && (qright < left))
      return Integer.MAX_VALUE;

      if((qleft <= left) || (qright >= right))
      return st[pos];

      int mid = (left + right) / 2;

      int l = rmq(left(pos), left, mid, qleft, qright);
      int r = rmq(right(pos), mid + 1, right, qleft, qright);

      return (l > r) ? r : l;
      }

      // show segment tree
      static void showArray(int arr) {

      for(Integer x : arr)
      System.out.print(x+" ");
      System.out.println();
      }
      }









      share|improve this question
















      I tried to implement segment tree algorithm for finding range minimum query in Java. Here is my complete java code. It builds the segment tree from an array. and then prints the minimum element in every range. the problem is, tree is correct (as far as I know), but the output is always the least element of whole array. :-| kindly point out where I am going wrong.



      public class Solution {

      static int arr = {-1, 2, 4, 0};
      static int st;

      public static void main(String args) {

      st = new int [ 2 * arr.length-1];

      buildTree(0, 0, arr.length-1);

      System.out.print("original array: ");
      showArray(arr);

      System.out.print("segment tree: ");
      // shows segment tree
      showArray(st);

      System.out.println("nqueries: n");

      // prints minimum in every range
      for(int i=0; i<arr.length; i++) {
      for(int j=i+1; j<arr.length; j++)
      System.out.println(i+":"+j+" -> "+search(i, j));
      }

      }

      // builds segment tree
      static void buildTree(int pos, int left, int right) {

      if(left == right) {
      st[pos] = arr[left];
      return;
      }

      int mid = (left + right) / 2;

      buildTree(left(pos), left, mid);
      buildTree(right(pos), mid+1, right);

      int p1 = left(pos);
      int p2 = right(pos);

      st[pos] = (st[p1] > st[p2]) ? st[p2] : st[p1];
      }

      // left child
      static int left(int pos) {
      return pos * 2 + 1;
      }

      // right child
      static int right(int pos) {
      return pos * 2 + 2;
      }

      static int search(int left, int right) {

      return rmq(0, 0, st.length, left, right);
      }

      // range minimum query function
      static int rmq(int pos, int left, int right, int qleft, int qright) {

      if((qleft > right) && (qright < left))
      return Integer.MAX_VALUE;

      if((qleft <= left) || (qright >= right))
      return st[pos];

      int mid = (left + right) / 2;

      int l = rmq(left(pos), left, mid, qleft, qright);
      int r = rmq(right(pos), mid + 1, right, qleft, qright);

      return (l > r) ? r : l;
      }

      // show segment tree
      static void showArray(int arr) {

      for(Integer x : arr)
      System.out.print(x+" ");
      System.out.println();
      }
      }






      algorithm data-structures segment-tree rmq






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 25 '18 at 11:55









      James Z

      11.2k71936




      11.2k71936










      asked Nov 25 '18 at 10:22









      Chetan RaikwarChetan Raikwar

      104




      104
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You have to make following changes in your code.



          First of all size of array used for storing data in segmentree datastructure should be 4 times of size of given array. Here is why?



          st = new int [ 4 * arr.length - 1];


          Next in search function, you third parameter for rmq must be arr.length - 1.



          static int search(int left, int right) {
          return rmq(0, 0, arr.length - 1, left, right);
          }


          And finally, you have to correct base cases and arguments in child calls in rmq function as follows:



          static int rmq(int pos, int left, int right, int qleft, int qright) {

          if((qleft > right) || (qright < left))
          return Integer.MAX_VALUE;

          if((qleft <= left) && (qright >= right))
          return st[pos];

          int mid = (left + right) / 2;

          int l = rmq(left(pos), left, mid, qleft, Math.min(qright, mid) );
          int r = rmq(right(pos), mid + 1, right, Math.max(mid + 1, qleft), qright);

          return (l > r) ? r : l;
          }


          Hope this helps.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53466563%2fsegment-tree-correct-but-query-output-is-not%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You have to make following changes in your code.



            First of all size of array used for storing data in segmentree datastructure should be 4 times of size of given array. Here is why?



            st = new int [ 4 * arr.length - 1];


            Next in search function, you third parameter for rmq must be arr.length - 1.



            static int search(int left, int right) {
            return rmq(0, 0, arr.length - 1, left, right);
            }


            And finally, you have to correct base cases and arguments in child calls in rmq function as follows:



            static int rmq(int pos, int left, int right, int qleft, int qright) {

            if((qleft > right) || (qright < left))
            return Integer.MAX_VALUE;

            if((qleft <= left) && (qright >= right))
            return st[pos];

            int mid = (left + right) / 2;

            int l = rmq(left(pos), left, mid, qleft, Math.min(qright, mid) );
            int r = rmq(right(pos), mid + 1, right, Math.max(mid + 1, qleft), qright);

            return (l > r) ? r : l;
            }


            Hope this helps.






            share|improve this answer




























              0














              You have to make following changes in your code.



              First of all size of array used for storing data in segmentree datastructure should be 4 times of size of given array. Here is why?



              st = new int [ 4 * arr.length - 1];


              Next in search function, you third parameter for rmq must be arr.length - 1.



              static int search(int left, int right) {
              return rmq(0, 0, arr.length - 1, left, right);
              }


              And finally, you have to correct base cases and arguments in child calls in rmq function as follows:



              static int rmq(int pos, int left, int right, int qleft, int qright) {

              if((qleft > right) || (qright < left))
              return Integer.MAX_VALUE;

              if((qleft <= left) && (qright >= right))
              return st[pos];

              int mid = (left + right) / 2;

              int l = rmq(left(pos), left, mid, qleft, Math.min(qright, mid) );
              int r = rmq(right(pos), mid + 1, right, Math.max(mid + 1, qleft), qright);

              return (l > r) ? r : l;
              }


              Hope this helps.






              share|improve this answer


























                0












                0








                0







                You have to make following changes in your code.



                First of all size of array used for storing data in segmentree datastructure should be 4 times of size of given array. Here is why?



                st = new int [ 4 * arr.length - 1];


                Next in search function, you third parameter for rmq must be arr.length - 1.



                static int search(int left, int right) {
                return rmq(0, 0, arr.length - 1, left, right);
                }


                And finally, you have to correct base cases and arguments in child calls in rmq function as follows:



                static int rmq(int pos, int left, int right, int qleft, int qright) {

                if((qleft > right) || (qright < left))
                return Integer.MAX_VALUE;

                if((qleft <= left) && (qright >= right))
                return st[pos];

                int mid = (left + right) / 2;

                int l = rmq(left(pos), left, mid, qleft, Math.min(qright, mid) );
                int r = rmq(right(pos), mid + 1, right, Math.max(mid + 1, qleft), qright);

                return (l > r) ? r : l;
                }


                Hope this helps.






                share|improve this answer













                You have to make following changes in your code.



                First of all size of array used for storing data in segmentree datastructure should be 4 times of size of given array. Here is why?



                st = new int [ 4 * arr.length - 1];


                Next in search function, you third parameter for rmq must be arr.length - 1.



                static int search(int left, int right) {
                return rmq(0, 0, arr.length - 1, left, right);
                }


                And finally, you have to correct base cases and arguments in child calls in rmq function as follows:



                static int rmq(int pos, int left, int right, int qleft, int qright) {

                if((qleft > right) || (qright < left))
                return Integer.MAX_VALUE;

                if((qleft <= left) && (qright >= right))
                return st[pos];

                int mid = (left + right) / 2;

                int l = rmq(left(pos), left, mid, qleft, Math.min(qright, mid) );
                int r = rmq(right(pos), mid + 1, right, Math.max(mid + 1, qleft), qright);

                return (l > r) ? r : l;
                }


                Hope this helps.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 25 '18 at 11:57









                Bishal GautamBishal Gautam

                835518




                835518
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53466563%2fsegment-tree-correct-but-query-output-is-not%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Create new schema in PostgreSQL using DBeaver

                    Deepest pit of an array with Javascript: test on Codility

                    Fotorealismo