java - Insertion Sort algorithm not working as expected -


my insertion sort code is:

class insertionsort {     public static void main(string s[])     {         int []a={12,5,8,87,55,4};         int []r=sort(a);         for(int i=0;i<a.length;i++)         {             system.out.println(r[i]);         }     }     static int[] sort(int a[])     {         int key,i,j;         for(j=1;j<a.length;j++)         {             key=a[j];             i=j-1;             while(i>=0 && a[j]<a[i])             {                 a[j]=a[i];                 i--;             }             a[i+1]=key;         }         return a;     } } 

but result not correct. however, if replace a[j] key in while loop condition , a[j] a[i+1] in while loop body, code generates correct result. there difference between a[j] , key , a[j] , a[i+1]?

correct code:

    static void sort(int a[])     {          for(int j = 1; j < a.length; j++)          {             int key = a[j];             int = j;             while(i > 0 && a[i-1] > key)             {                 a[i] = a[i-1];                 i--;             }             a[i] = key;          }     } 

note don't have return since method changes input array.

q: there difference in a[j] , key or a[j] , a[i+1]?

of course. whole point of insertion sort algorithm exchanges current element elements on left hand side greater it. imagine rearranging cards in hand. in original version, j fixed in inner loop , rearranging not happen.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -