-1

I'm writing a simple program to sort a small array but when I run my code for insertion sort the program just runs forever.

It's probably a problem with the while loop. I ran through the program on paper and looked over some other people's code but I can't figure out why it's not working.

void mySort(int d[], unsigned int n){   
        int i, j, k;
        for (j = 1;j < n;i++){
        k = d[j];
        i = j-1;

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

2 Answers2

0
for (j = 1;j < n;i++){

You compare value j, but you increment value i.

If you Use a Debugger, you would immediately notice that the value j does not get updated, and you'd find your problem immediately!!

Always Use a Debugger

abelenky
  • 63,815
  • 23
  • 109
  • 159
0

The error is in your for loop.

for (j = 1;j < n;i++){

So your terminating conditions of the for loop are that j >= n, except you never change j or n after this statement.

Try

for (j = 1;j < n;j++){
Daniel
  • 854
  • 7
  • 18