c++ - Insertion sort on strings -


i trying sort array of strings according middle 3 characters using insertion sort.

the code compiles crashes while running

i sorting array of middle 3 character , sorting array stores index of strings. while printing final result can sorted array

void ins(string a[size],int n) {     int i,j,k,length[size],index[size],m,t;     string temp,ts[size];      // ts[] stores middle 3 characters     for(i=0;i<n;i++)     {         index[i]=i;     }     for(i=0;i<n;i++)     {         length[i]=a[i].length();     }     for(i=0;i<n;i++)     {         m=length[i]/2;         ts[i]=a[i].substr(m-1,3);     }     for(i=0;i<n;i++)         cout<<ts[i]<<endl;     for(k=1;k<n;k++)     {         temp=ts[k];         t=index[k];         j=k-1;         while((temp < ts[j]) && (j>=0))         {             ts[j+1]=ts[j];             index[j+1]=index[j];             j=j-1;         }          ts[j+1]=temp;         index[j+1]=t;     }     for(i=0;i<n;i++)     {         cout<<a[index[i]]<<endl;     } } 

main

int main() {     int n,i,j,k,num;     string a[size];     cin>>n;     for(i=0;i<n;i++)     {         cin>>a[i];     }     ins(a,n); } 

can please me find bug

in expression of form left-condition && right-condition:

  1. the left-condition evaluated first;
  2. what happens next depends on result of evaluation of left-condition:
    1. if left-condition true, right-condition evaluated in second.
    2. if left-condition false, evaluation of right-condition skipped.

in case, problems lies expression (temp < ts[j]) && (j>=0) since implements following behavior:

  1. you first use ts[j] in left expression;
  2. then test in right-expression j>=0, ts[j] not out-of-bounds.

the solution exchange positions of these expressions , write expression as: (j >= 0 && temp < ts[j]).


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -