/* * bugsort.c - a buggy implementation of insertion sort * * This program was developed to demonstrate gdb for debugging. * * usage: bugsort < inputfile * where the stdin is assumed to include a sequence of numbers. * * David Kotz 2019, 2021 * Tim Pierson, 2022 * CS 50, Fall 2022 */ #include #include /* ******************* main ***************** */ int main() { const int numSlots = 10; // number of slots in array int sorted[numSlots]; // the array of items /* fill the array with numbers */ for (int n = 0; n < numSlots; n++) { //n counts how many items stored int item; // a new item scanf("%d", &item); // read a new item int i = n; //fix: declare i outside loop so we can use it below for (i = n; i > 0; i--) { //do not enter when n=0 if (sorted[i-1] > item) { //last item inserted at n-1 sorted[i] = sorted[i-1]; // bump it up to make room } else { break; //fix: break out of loop when no need to move } } sorted[i] = item; // drop the new item here } /* print the numbers */ for (int n = 0; n < numSlots; n++) { printf("%d ", sorted[n]); } putchar('\n'); }