Q:

c++ string subscript out of range

Please help with debugging. It gives me an error 'string subscript out of range error'.
The program needs to sort the text using insertion sort algorithm.
Here is the code:
#include<iostream>
#include<string>
using namespace std;

void insertionSort(string &text, int size) {
  char temp;
  int i;
  for(int j=1;j<size;j++)
  {
    //text.push_back(temp);
    temp=text[j];
    i=j-1;
   while(i>=0 && text[i]>temp)
 {

 text[i+1]=text[i];
  i--;
 }
    text[i+1]=temp;
  }
}

int main()
{
  string text="this a just text need to be sorted";

  int size = text.length();
  insertionSort(text,size);
  cout<<text<<endl;
  return 0;
}

debug assertion Failed!
Line:1441:
Expression: string subscript out of range
I supposed to change text[i+1]=text[j]  to text[i+1]=text[i];

A:

You have to change this instruction:
text[i+1]=text[i];

A:

Replace
while(text[i]>temp && i>=0)

with 
while(i>=0 && text[i]>temp)

Reason:
When i becomes negative, ie i == -1, then first check for i>=0 instead of doing check for text[i]>temp (which tries to access array element at position -1 and gives out of range).
EDIT:
also replace
text[i+1]=text[j];

with 
text[i+1]=text[i];

Why so ? : In insertion sort if we have entries greater than text[j] in the lower part (ie. 0 to j-1), then we need to push these entries ahead and stop at point when we no longer have elements bigger than text[j].

