Reputation: 177
Insertion sort is not working, it is only printing some of the values. Does anyone know what I can do to fix it?
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
int j = i;
while (j >= 0 && Array[j] < Array[j - 1]) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
j--;
}
}
}
Upvotes: 0
Views: 95
Reputation: 23
Insertion Sort: Idea
Similar to how most people arrange a hand of poker cards
Start with one card in your hand
Pick the next card and insert it into its proper sorted order
Repeat previous step for all cards
Upvotes: 0
Reputation: 144923
The test in the inner loop is incorrect: when j == 0
you read and possibly modify the element at offset -1
, which has undefined behavior, possibly causing the incorrect output, but since you did not post the output code, there might be other problems there.
Here is a modified version:
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && Array[j] < Array[j - 1]; j--) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
}
}
}
Upvotes: 1