0

Can I sort a sub-array of a given 2-D array using qsort() function in C. For example, say I have a 2-D array char arr[2*m][n]. Can I sort the 2-D sub-array char arr[0...m][n] in the lexicographic order, instead of sorting the whole array?

HarshitR
  • 31
  • 5
  • Well, you do tell `qsort` how many elements to sort.... – Weather Vane Jun 09 '17 at 18:10
  • 1
    Refer this page [C qsort() with dynamic n by 2 multi-dimensional array](https://stackoverflow.com/a/17202664/6202039) – Jay Patel Jun 09 '17 at 18:11
  • 2
    The answer to "can I do x" in C is always yes. – diatrevolo Jun 09 '17 at 18:13
  • *the lexicographic order* of a 2-D `char` array suggests you have an array of strings to sort. Just tell `qsort` you have `m` elements instead of the `2*m` elements defined. – Weather Vane Jun 09 '17 at 18:25
  • @WeatherVane Actually, my question is that if I have to sort any random sub-array, say `char arr[m...2*m][n]`, then it is fine to me that I will pass the number of elements (here m) as argument, but how would I tell qsort() which sub-array to sort, i.e.whether I have to sort `char arr[0...m][n]` or `char arr[m...2*m][n]` or `char arr[3...m+3][n]`, etc.? – HarshitR Jun 09 '17 at 18:26
  • You also pass the base address, enabling you to sort elements `p` to `q`. In this case, the address of element `p` with `q - p + 1` items in the array. – Weather Vane Jun 09 '17 at 18:27
  • `qsort(arr, m+1 /* if you want half, m */, sizeof(*arr), compar);` – BLUEPIXY Jun 09 '17 at 19:41
  • e.g arr[3][n]-arr[3+m][n] (m+1 element), `qsort(arr+3, m+1, sizeof(*arr), compar);` – BLUEPIXY Jun 09 '17 at 19:46

0 Answers0