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












7















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





























    7















    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



























      7












      7








      7


      1






      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
















      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















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 2 at 16:11









      Peter Mortensen

      13.5k1984111




      13.5k1984111










      asked Jan 2 at 9:12









      nglunglu

      413




      413
























          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
            Jan 2 at 9:18











          • @SagiRika Oops! fixed.

            – Sweeper
            Jan 2 at 9:19











          • give a code example for clarity and I think this should be accepted as answer.

            – Murat Güvenç
            Jan 2 at 9:22











          • @MuratGüvenç Is it clearer now?

            – Sweeper
            Jan 2 at 9:26











          • I think it is :) It is up to @nglu to accept this.

            – Murat Güvenç
            Jan 2 at 10:03











          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%2f54003731%2fwhy-is-there-a-difference-between-two-similar-implementations-of-a-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
            Jan 2 at 9:18











          • @SagiRika Oops! fixed.

            – Sweeper
            Jan 2 at 9:19











          • give a code example for clarity and I think this should be accepted as answer.

            – Murat Güvenç
            Jan 2 at 9:22











          • @MuratGüvenç Is it clearer now?

            – Sweeper
            Jan 2 at 9:26











          • I think it is :) It is up to @nglu to accept this.

            – Murat Güvenç
            Jan 2 at 10:03
















          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
            Jan 2 at 9:18











          • @SagiRika Oops! fixed.

            – Sweeper
            Jan 2 at 9:19











          • give a code example for clarity and I think this should be accepted as answer.

            – Murat Güvenç
            Jan 2 at 9:22











          • @MuratGüvenç Is it clearer now?

            – Sweeper
            Jan 2 at 9:26











          • I think it is :) It is up to @nglu to accept this.

            – Murat Güvenç
            Jan 2 at 10:03














          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 Jan 2 at 9:25

























          answered Jan 2 at 9:16









          SweeperSweeper

          65.1k1071139




          65.1k1071139













          • k is iterated down, k-- not k++.

            – Sagi Rika
            Jan 2 at 9:18











          • @SagiRika Oops! fixed.

            – Sweeper
            Jan 2 at 9:19











          • give a code example for clarity and I think this should be accepted as answer.

            – Murat Güvenç
            Jan 2 at 9:22











          • @MuratGüvenç Is it clearer now?

            – Sweeper
            Jan 2 at 9:26











          • I think it is :) It is up to @nglu to accept this.

            – Murat Güvenç
            Jan 2 at 10:03



















          • k is iterated down, k-- not k++.

            – Sagi Rika
            Jan 2 at 9:18











          • @SagiRika Oops! fixed.

            – Sweeper
            Jan 2 at 9:19











          • give a code example for clarity and I think this should be accepted as answer.

            – Murat Güvenç
            Jan 2 at 9:22











          • @MuratGüvenç Is it clearer now?

            – Sweeper
            Jan 2 at 9:26











          • I think it is :) It is up to @nglu to accept this.

            – Murat Güvenç
            Jan 2 at 10:03

















          k is iterated down, k-- not k++.

          – Sagi Rika
          Jan 2 at 9:18





          k is iterated down, k-- not k++.

          – Sagi Rika
          Jan 2 at 9:18













          @SagiRika Oops! fixed.

          – Sweeper
          Jan 2 at 9:19





          @SagiRika Oops! fixed.

          – Sweeper
          Jan 2 at 9:19













          give a code example for clarity and I think this should be accepted as answer.

          – Murat Güvenç
          Jan 2 at 9:22





          give a code example for clarity and I think this should be accepted as answer.

          – Murat Güvenç
          Jan 2 at 9:22













          @MuratGüvenç Is it clearer now?

          – Sweeper
          Jan 2 at 9:26





          @MuratGüvenç Is it clearer now?

          – Sweeper
          Jan 2 at 9:26













          I think it is :) It is up to @nglu to accept this.

          – Murat Güvenç
          Jan 2 at 10:03





          I think it is :) It is up to @nglu to accept this.

          – Murat Güvenç
          Jan 2 at 10:03


















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

          MongoDB - Not Authorized To Execute Command

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

          How to fix TextFormField cause rebuild widget in Flutter