Levent Kaya
Levent Kaya

Reputation: 47

Comparing previous array elements for Insertion Sort algorithm

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.

Upvotes: 1

Views: 54

Answers (1)

chqrlie
chqrlie

Reputation: 144820

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.

Upvotes: 1

Related Questions