Reputation: 47
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
Reputation: 144820
The posted code has multiple problems:
j > 0
instead of j <= 0
.pseudoJ
to avoid accessing elements before the beginning of the arrayj
in the outer loop and decrement i
in the inner loop. The name pseudoJ
is confusing.Upvotes: 1