Advertisement
aaaaaa123456789

Testing code for JV's programming challenge week 2

Nov 18th, 2012
58
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void sort (int *, unsigned);
  5.  
  6. int main (void) {
  7.   int * array = NULL;
  8.   unsigned length = 0;
  9.   printf("Input a number, anything invalid to quit: ");
  10.   int entry;
  11.   int status;
  12.   for (status = scanf("%d", &entry); status; status = scanf("%d", &entry)) {
  13.     array = realloc(array, sizeof(int) * (length ++));
  14.     array[length - 1] = entry;
  15.     printf("Input a number, anything invalid to quit: ");
  16.   }
  17.   sort(array, length);
  18.   printf("Result: ");
  19.   for (entry = 0; entry < length; entry ++) printf("%d ", array[entry]);
  20.   putchar('\n');
  21.   free(array);
  22.   return 0;
  23. }
  24.  
  25. void sort (int * array, unsigned arrayLength) {
  26.   int * first = array;
  27.   int * last = array + (arrayLength - 1);
  28.   int * current = first;
  29.   int temp;
  30.   while (first != last) {
  31.     if (*first < *last) {
  32.       temp = *first;
  33.       *first = *last;
  34.       *last = temp;
  35.       current = (current == first) ? last : first;
  36.     }
  37.     if (current == last)
  38.       first ++;
  39.     else
  40.       last --;
  41.   }
  42.   if ((current - array) > 1)
  43.     if ((current - array) == 2) {
  44.       if (*array < array[1]) {
  45.         temp = *array;
  46.         *array = array[1];
  47.         array[1] = *array;
  48.       }
  49.     } else
  50.       sort(array, current - array);
  51.   if ((current - array) < (arrayLength - 2))
  52.     if ((current - array) == (arrayLength - 3)) {
  53.       if (current[1] < current[2]) {
  54.         temp = current[1];
  55.         current[1] = current[2];
  56.         current[2] = temp;
  57.       }
  58.     } else
  59.       sort(current + 1, arrayLength - 1 - (current - array));
  60. }
Advertisement
RAW Paste Data Copied
Advertisement