C-Kurs/BubbleSortDebug: Unterschied zwischen den Versionen
< C-Kurs
Zeile 3: | Zeile 3: | ||
<pre> | <pre> | ||
− | + | #include <stdio.h> | |
− | + | typedef struct | |
− | + | { | |
− | + | char *data; | |
− | + | int key; | |
− | + | } item; | |
− | + | ||
− | + | item array[] = { | |
− | + | {"bill", 3}, | |
− | + | {"neil", 4}, | |
− | + | {"john", 2}, | |
− | + | {"rick", 5}, | |
− | + | {"alex", 1}, | |
− | + | }; | |
− | + | ||
− | + | void sort(item *paItems, unsigned cItems) { | |
− | + | int i = 0, j = 0; | |
− | + | int s = 1; | |
− | + | ||
− | + | for (i = 0; i < cItems && s != 0; i++) { | |
− | + | s = 0; | |
− | + | for (j = 0; j < cItems; j++){ | |
− | + | if (paItems[j].key > paItems[j+1].key) { | |
− | + | item Temp = paItems[j]; | |
− | + | paItems[j] = paItems[j+1]; | |
− | + | paItems[j+1] = Temp; | |
− | + | s++; | |
− | + | } | |
− | + | } | |
− | + | cItems--; | |
− | + | } | |
− | + | } | |
− | + | ||
− | + | int main(void) { | |
− | + | int i = 0; | |
− | + | sort(array, 5); | |
− | + | for (i = 0; i < 5; i++) { | |
− | + | printf("array[%d] == {%s, %d}\n", i, array[i].data, array[i].key); | |
− | + | } | |
− | + | } | |
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
</pre> | </pre> |
Version vom 23. September 2009, 12:28 Uhr
Das folgende Programm, welches ein Array von Elementen mit Hilfe von Bubblesort sortiert enthält verschiedene Bugs: Debugge es mit printf,assert und/oder gdb, so dass es wie gewünscht funktioniert:
#include <stdio.h> typedef struct { char *data; int key; } item; item array[] = { {"bill", 3}, {"neil", 4}, {"john", 2}, {"rick", 5}, {"alex", 1}, }; void sort(item *paItems, unsigned cItems) { int i = 0, j = 0; int s = 1; for (i = 0; i < cItems && s != 0; i++) { s = 0; for (j = 0; j < cItems; j++){ if (paItems[j].key > paItems[j+1].key) { item Temp = paItems[j]; paItems[j] = paItems[j+1]; paItems[j+1] = Temp; s++; } } cItems--; } } int main(void) { int i = 0; sort(array, 5); for (i = 0; i < 5; i++) { printf("array[%d] == {%s, %d}\n", i, array[i].data, array[i].key); } }