1

I'm working with insertion sort algorithm. As you know we need to compare array elements with previous array elements. I try to do this with nested loops:

scanf("%d", &size); //gets array size

int array[size];
int temp = 0;

for (int i = 0; i < size; i++) {
    scanf("%d", &array[i]);
} // Takes the index of array.

/*
 Sorting part begins.
 */

for (int j = size - 1; j <= 0; j--) {
    int pseudoJ;

    pseudoJ = j;

    while (1) {
        if (array[pseudoJ] < array[pseudoJ - 1]) {
            temp = array[pseudoJ];
            array[pseudoJ] = array[pseudoJ - 1];
            array[pseudoJ - 1] = temp;
            pseudoJ--;
        } else
            break;
    }  
}

/*
 * Sorting Par Ends.
 */

Assume that input is: 3(Array Elements)>3>2>1, I expected the output of 1>2>3 but the output is still 3>2>1.

4
  • Have you tried stepping through the code using a debugger? Commented Apr 5, 2019 at 7:54
  • No, I didn't let me look with gdb.. Commented Apr 5, 2019 at 7:55
  • 4
    Take a very good look at the boundary condition of your second for loop. Commented Apr 5, 2019 at 7:55
  • Yes, when I change few lines of code it compares the previous array element but did not compare with all the previous ones.. Commented Apr 5, 2019 at 7:57

1 Answer 1

1

The posted code has multiple problems:

  • the outer loop exits immediately: the test should be j > 0 instead of j <= 0.
  • the inner loop should test pseudoJ to avoid accessing elements before the beginning of the array
  • it would be simpler to increment the index j in the outer loop and decrement i in the inner loop. The name pseudoJ is confusing.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for contribution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.