问题
I am making a c insertion sort and it works fine except that after the sort the first number is always a weird negative number and the program errors out.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insertionSort(int list[], int last){
int hold;
int walker;
int current;
int count;
count = 0;
for (current = 1; current <= last; current++){
hold = list[current];
for (walker = current - 1;
walker >= 0 && hold < list[walker]; walker--){
list[walker + 1] = list[walker];
}
list [walker + 1] = hold;
count++;
}
printf("\n\nHow many passes to sort?\n%d\n\n", count);
return;
}
int main(int argc, char *argv[])
{
int numbers[100];
int i;
srand(time(NULL));
for (i = 0; i < 100; i++){
numbers[i] = rand() % 100;
}
printf("Unsorted Numbers\n-------- -------\n");
for (i = 0; i < 100; i++){
printf("%d,", numbers[i]);
}
insertionSort(numbers, 100);
printf("\nSorted Numbers\n-------- -------\n");
for (i = 0; i < 100; i++){
printf("%d,", numbers[i]);
}
system("PAUSE");
return 0;
}
回答1:
You are going OVER the array size within the loop. When current = last, list[last] is list[100], the 101th element of the array... this is also not good.
Edit. I just tested this out and it worked for me. Only thing i changed was the <= in the outer loop to n <
void insertionSort(int list[], int last){
int hold;
int walker;
int current;
int count;
count = 0;
for (current = 1; current < last; current++){
hold = list[current];
for (walker = current - 1;
walker >= 0 && hold < list[walker]; walker--){
list[walker + 1] = list[walker];
}
list [walker + 1] = hold;
count++;
}
printf("\n\nHow many passes to sort?\n%d\n\n", count);
return;
}
回答2:
If you declare an array like
int numbers[100]
numbers[99] is the last element. In your sort function you are accessing numbers[100] as well.
来源:https://stackoverflow.com/questions/8045733/error-with-c-insertion-sort