#include #include #include int i, size; int *table; char c; int insertionSort (int *, int); int selectionSort (int *, int); int checkSorted (int *, int); int main () { while (1) { printf ("Select a number:\n"); printf ("1) Randomly fill the table\n"); printf ("2) print the table\n"); printf ("3) selection sort\n"); printf ("4) insertion sort\n"); printf ("5) check the table is sorted\n"); printf ("6) exit\n"); char *s = NULL; do { fprintf (stdout, "Make your selection: "); while ((c = getchar ()) == '\n'); } while (!strchr ("123456", c)); switch (c) { case '1': srand (1); printf ("please enter the size of the table:"); scanf ("%d", &size); fflush (stdin); table = malloc (size * sizeof (int)); for (i = 0; i < size; i++) table[i] = random () % 1024; break; case '2': printf ("\n\nThe table:["); for (i = 0; i < size - 1; i++) printf ("%d,", table[i]); printf ("%d]\n\n", table[i]); break; case '3': selectionSort (table, size); break; case '4': insertionSort (table, size); break; case '5': checkSorted (table, size); break; case '6': return (1); break; } } return (1); } int selectionSort (int array[], int size) { int i, j; int min, temp; for (i = 0; i < size - 1; i++) { min = i; for (j = i + 1; j < size; j++) { if (table[j] < array[min]) min = j; } temp = array[i]; array[i] = array[min]; array[min] = temp; } return (1); } int insertionSort (int a[], int size) { int i, j, val; for (i = 0; i < size; i++) { val = a[i]; j = i - 1; while (j >= 0 && a[j] > val) { a[j + 1] = a[j]; j--; } a[j + 1] = val; } return (1); } int checkSorted (int array[], int size) { int i, unsorted = 0; for (i = 1; i < size; i += 1) { if (array[i - 1] > array[i]) { printf ("The array is not in sorted order at position %d\n", i - 1); if (!unsorted) unsorted++; } } if (!unsorted) printf ("\nThe table is already sorted !\n"); return (1); }