sorting array of strings

I am attempting to sort array of string with insertion sort alghoritam
but i got run time error, problem is in variable i, in while loop
when insted it in while condition put some number it work ....help....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const int max=5;

  string niz[max];

  niz[0]="am";
  niz[1]="ss";
  niz[2]="bd";
  niz[3]="af";
  niz[4]="cf";
     
	  
    string temp;
	int i;

	  for(int j=1;j<max;j++)
	  {
		  temp=niz[j];
		  i=j-1;		  

		   while(niz[i]>temp && i>=0)
		  {
			  niz[i+1]=niz[i];
			  i--;
		  }  ;

		  
		  niz[i+1]=temp;
	  }


 for(int i=0;i<max;i++)
	 cout<<niz[i]<<endl;


Last edited on
actually
while(niz[i]>temp && i>=0)
{
niz[i+1]=niz[i];
i--;
} ;
this loop is checking for the last value of niz array as well so if it find that if the first element is >temp. i.e niz[0]>temp then it will enter the loop and execute i--
which is being happening in your code as "af" <"am"
so what you can do is make it i>0 i.e

while(niz[i]>temp && i>=0) and explicitly check for niz[0] and niz[1] position or
you can take niz[0] to be smallest for niz all(for the sake of running the program)


hope this will help as this is my first posted solution :)
Last edited on
Topic archived. No new replies allowed.