Why is there a difference between two similar implementations of for-loop?












6














I'm trying to write an insertion sort method and I have managed to finish it, but I don't understand why my first version cannot work correctly.



Here's my first attempt:



public static void insertionSort(int list) {
for (int i = 1; i < list.length; i++) {
int current = list[i];
for (int k = i - 1; k >= 0 && current < list[k]; k--) {
list[i] = list[k];
list[k] = current;
}
}
}

public static void main(String args) {
int list = {8, 22, 90, 10};
insertionSort(list);
}


My output for the above code is: 8, 10, 10, 22



But the answer would be correct if the inside for-loop, at line 5, is changed from:list[i] = list[k];
to: list[k + 1] = list[k];



To my understanding, k + 1 is equal to i, but it must be different in loop counting and I can't figure out how. I have tried many sets of input, and only values that lie between the range of the 2 first indexes (in this case 8 and 22) would be incorrect.










share|improve this question









New contributor




nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    6














    I'm trying to write an insertion sort method and I have managed to finish it, but I don't understand why my first version cannot work correctly.



    Here's my first attempt:



    public static void insertionSort(int list) {
    for (int i = 1; i < list.length; i++) {
    int current = list[i];
    for (int k = i - 1; k >= 0 && current < list[k]; k--) {
    list[i] = list[k];
    list[k] = current;
    }
    }
    }

    public static void main(String args) {
    int list = {8, 22, 90, 10};
    insertionSort(list);
    }


    My output for the above code is: 8, 10, 10, 22



    But the answer would be correct if the inside for-loop, at line 5, is changed from:list[i] = list[k];
    to: list[k + 1] = list[k];



    To my understanding, k + 1 is equal to i, but it must be different in loop counting and I can't figure out how. I have tried many sets of input, and only values that lie between the range of the 2 first indexes (in this case 8 and 22) would be incorrect.










    share|improve this question









    New contributor




    nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      6












      6








      6







      I'm trying to write an insertion sort method and I have managed to finish it, but I don't understand why my first version cannot work correctly.



      Here's my first attempt:



      public static void insertionSort(int list) {
      for (int i = 1; i < list.length; i++) {
      int current = list[i];
      for (int k = i - 1; k >= 0 && current < list[k]; k--) {
      list[i] = list[k];
      list[k] = current;
      }
      }
      }

      public static void main(String args) {
      int list = {8, 22, 90, 10};
      insertionSort(list);
      }


      My output for the above code is: 8, 10, 10, 22



      But the answer would be correct if the inside for-loop, at line 5, is changed from:list[i] = list[k];
      to: list[k + 1] = list[k];



      To my understanding, k + 1 is equal to i, but it must be different in loop counting and I can't figure out how. I have tried many sets of input, and only values that lie between the range of the 2 first indexes (in this case 8 and 22) would be incorrect.










      share|improve this question









      New contributor




      nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I'm trying to write an insertion sort method and I have managed to finish it, but I don't understand why my first version cannot work correctly.



      Here's my first attempt:



      public static void insertionSort(int list) {
      for (int i = 1; i < list.length; i++) {
      int current = list[i];
      for (int k = i - 1; k >= 0 && current < list[k]; k--) {
      list[i] = list[k];
      list[k] = current;
      }
      }
      }

      public static void main(String args) {
      int list = {8, 22, 90, 10};
      insertionSort(list);
      }


      My output for the above code is: 8, 10, 10, 22



      But the answer would be correct if the inside for-loop, at line 5, is changed from:list[i] = list[k];
      to: list[k + 1] = list[k];



      To my understanding, k + 1 is equal to i, but it must be different in loop counting and I can't figure out how. I have tried many sets of input, and only values that lie between the range of the 2 first indexes (in this case 8 and 22) would be incorrect.







      java






      share|improve this question









      New contributor




      nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 4 hours ago









      deHaar

      2,15631527




      2,15631527






      New contributor




      nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 4 hours ago









      nglu

      342




      342




      New contributor




      nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      nglu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          1 Answer
          1






          active

          oldest

          votes


















          7














          k + 1 is equal to i, but only in the first iteration of the inner for loop. int k = i - 1 is only run once per iteration of the outer for loop.



          In the second iteration of the inner for loop, k is decremented but i is not. Therefore, k + 1 and i are not interchangeable inside the inner for loop.



          // second iteration of the outer for loop, second iteration of the inner for loop:
          list[i] = list[k]; // means "list[2] = list[0]
          // whereas
          list[k + 1] = list[k]; // means "list[1] = list[0]"





          share|improve this answer























          • k is iterated down, k-- not k++.
            – Sagi Rika
            4 hours ago










          • @SagiRika Oops! fixed.
            – Sweeper
            4 hours ago










          • give a code example for clarity and I think this should be accepted as answer.
            – Murat Güvenç
            4 hours ago










          • @MuratGüvenç Is it clearer now?
            – Sweeper
            4 hours ago










          • I think it is :) It is up to @nglu to accept this.
            – Murat Güvenç
            3 hours ago











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


          }
          });






          nglu is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54003731%2fwhy-is-there-a-difference-between-two-similar-implementations-of-for-loop%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









          7














          k + 1 is equal to i, but only in the first iteration of the inner for loop. int k = i - 1 is only run once per iteration of the outer for loop.



          In the second iteration of the inner for loop, k is decremented but i is not. Therefore, k + 1 and i are not interchangeable inside the inner for loop.



          // second iteration of the outer for loop, second iteration of the inner for loop:
          list[i] = list[k]; // means "list[2] = list[0]
          // whereas
          list[k + 1] = list[k]; // means "list[1] = list[0]"





          share|improve this answer























          • k is iterated down, k-- not k++.
            – Sagi Rika
            4 hours ago










          • @SagiRika Oops! fixed.
            – Sweeper
            4 hours ago










          • give a code example for clarity and I think this should be accepted as answer.
            – Murat Güvenç
            4 hours ago










          • @MuratGüvenç Is it clearer now?
            – Sweeper
            4 hours ago










          • I think it is :) It is up to @nglu to accept this.
            – Murat Güvenç
            3 hours ago
















          7














          k + 1 is equal to i, but only in the first iteration of the inner for loop. int k = i - 1 is only run once per iteration of the outer for loop.



          In the second iteration of the inner for loop, k is decremented but i is not. Therefore, k + 1 and i are not interchangeable inside the inner for loop.



          // second iteration of the outer for loop, second iteration of the inner for loop:
          list[i] = list[k]; // means "list[2] = list[0]
          // whereas
          list[k + 1] = list[k]; // means "list[1] = list[0]"





          share|improve this answer























          • k is iterated down, k-- not k++.
            – Sagi Rika
            4 hours ago










          • @SagiRika Oops! fixed.
            – Sweeper
            4 hours ago










          • give a code example for clarity and I think this should be accepted as answer.
            – Murat Güvenç
            4 hours ago










          • @MuratGüvenç Is it clearer now?
            – Sweeper
            4 hours ago










          • I think it is :) It is up to @nglu to accept this.
            – Murat Güvenç
            3 hours ago














          7












          7








          7






          k + 1 is equal to i, but only in the first iteration of the inner for loop. int k = i - 1 is only run once per iteration of the outer for loop.



          In the second iteration of the inner for loop, k is decremented but i is not. Therefore, k + 1 and i are not interchangeable inside the inner for loop.



          // second iteration of the outer for loop, second iteration of the inner for loop:
          list[i] = list[k]; // means "list[2] = list[0]
          // whereas
          list[k + 1] = list[k]; // means "list[1] = list[0]"





          share|improve this answer














          k + 1 is equal to i, but only in the first iteration of the inner for loop. int k = i - 1 is only run once per iteration of the outer for loop.



          In the second iteration of the inner for loop, k is decremented but i is not. Therefore, k + 1 and i are not interchangeable inside the inner for loop.



          // second iteration of the outer for loop, second iteration of the inner for loop:
          list[i] = list[k]; // means "list[2] = list[0]
          // whereas
          list[k + 1] = list[k]; // means "list[1] = list[0]"






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 4 hours ago

























          answered 4 hours ago









          Sweeper

          64.1k1071138




          64.1k1071138












          • k is iterated down, k-- not k++.
            – Sagi Rika
            4 hours ago










          • @SagiRika Oops! fixed.
            – Sweeper
            4 hours ago










          • give a code example for clarity and I think this should be accepted as answer.
            – Murat Güvenç
            4 hours ago










          • @MuratGüvenç Is it clearer now?
            – Sweeper
            4 hours ago










          • I think it is :) It is up to @nglu to accept this.
            – Murat Güvenç
            3 hours ago


















          • k is iterated down, k-- not k++.
            – Sagi Rika
            4 hours ago










          • @SagiRika Oops! fixed.
            – Sweeper
            4 hours ago










          • give a code example for clarity and I think this should be accepted as answer.
            – Murat Güvenç
            4 hours ago










          • @MuratGüvenç Is it clearer now?
            – Sweeper
            4 hours ago










          • I think it is :) It is up to @nglu to accept this.
            – Murat Güvenç
            3 hours ago
















          k is iterated down, k-- not k++.
          – Sagi Rika
          4 hours ago




          k is iterated down, k-- not k++.
          – Sagi Rika
          4 hours ago












          @SagiRika Oops! fixed.
          – Sweeper
          4 hours ago




          @SagiRika Oops! fixed.
          – Sweeper
          4 hours ago












          give a code example for clarity and I think this should be accepted as answer.
          – Murat Güvenç
          4 hours ago




          give a code example for clarity and I think this should be accepted as answer.
          – Murat Güvenç
          4 hours ago












          @MuratGüvenç Is it clearer now?
          – Sweeper
          4 hours ago




          @MuratGüvenç Is it clearer now?
          – Sweeper
          4 hours ago












          I think it is :) It is up to @nglu to accept this.
          – Murat Güvenç
          3 hours ago




          I think it is :) It is up to @nglu to accept this.
          – Murat Güvenç
          3 hours ago










          nglu is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          nglu is a new contributor. Be nice, and check out our Code of Conduct.













          nglu is a new contributor. Be nice, and check out our Code of Conduct.












          nglu is a new contributor. Be nice, and check out our Code of Conduct.
















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f54003731%2fwhy-is-there-a-difference-between-two-similar-implementations-of-for-loop%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

          Understanding the information contained in the Deep Space Network XML data?

          Ross-on-Wye

          Eastern Orthodox Church