Advertisement
bennyp

SegFault on line 26

Mar 2nd, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. /**
  2.  * Sorts array of n values.
  3.  */
  4. void sort(int values[], int n)
  5. {
  6.     // At Zamyla's suggestion, we implement the Counting Sort algorithm
  7.     // Step 1: Zero-initialize array of LIMIT size.
  8.     static int count[65537];
  9.     int output[n];
  10.  
  11.     // Step 2: increment the counting element at index values[i] each
  12.     // time that value appears in values.
  13.     for (int i = 0; i < n; i++) {
  14.         count[values[i]]++;
  15.     }
  16.     // Step 3: To determine where to place each element, we can calculate the
  17.     // number of elements with a lower value, we do this by incrementing each
  18.     // value in the count array by the previous value.
  19.     for (int i = 1; i <= LIMIT; i++) {
  20.         count[i] += count[i - 1];
  21.     }
  22.     // Step 4: Place each item in the input array at the index of the output
  23.     // array that was specified in the count array, subtracting 1 from the
  24.     // counting array value each time so we avoid overwriting.
  25.     for (int i = n; i >= 0; i--) {
  26.         output[count[values[i]]] = values[i];
  27.         if (count[values[i]] > 0) count[values[i]]--;
  28.     }
  29.     // Step 5: Copy values from output array to input array
  30.     for (int i = 0; i < n; i++) {
  31.         values[i] = output[i];
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement