java - insertion sort program not working properly -


     public static void insertionsort(int[] arr) {          // each outer loop iteration inserts arr[i] correct location of         // already-sorted sub-list: arr[0] through arr[i-1]              (int = 1; < arr.length; i++) {                 int valuetoinsert = arr[i];                 int loc = 0;                 while (loc < && arr[loc] < valuetoinsert) {                      loc++;                  }                 (int j = loc; j < i; j++) {                      arr[j+1] = arr[j]; // issue                                  // loop i'm overriding next element                 }             arr[loc] = valuetoinsert; //// put value                                         //in correct location in sub-list          }      } 

above insertion sort code, not working properly, sample input given below

input [3, 9, 2] expected output [2, 3, 9] i'm getting [2, 3, 3] 

please let me more problem regarding insertion sort , quick response solicited

the problem

for (int j = loc; j < i; j++) {      arr[j+1] = arr[j];  } 

the previous value in array cover next one. should be

for (int j = i-1; j >= loc; j--) {      arr[j+1] = arr[j];  } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -