fork download
  1. #include <stdio.h>
  2.  
  3. void Qsort(
  4. void* sup,
  5. int n,
  6. int size,
  7. int(*cmp) (const void *x, const void *y),
  8. void (*swap) (void *a,void *b))
  9. {
  10. int pv = n / 2, l = 0, h = n - 1;
  11.  
  12. if (n < 2)
  13. return;
  14.  
  15. while (h - 1 >= l)
  16. {
  17. if (l == pv)
  18. {
  19. swap((char*)sup + pv * size, (char*)sup + (pv + 1) * size);
  20. pv++;
  21. }
  22.  
  23. if(h == pv)
  24. {
  25. swap((char*)sup + pv * size, (char*)sup + (pv - 1) * size);
  26. pv--;
  27. }
  28.  
  29. if (cmp((char*)sup + h * size, (char*)sup + pv * size) > 0)
  30. {
  31. h--;
  32. continue;
  33. }
  34.  
  35. if (cmp((char*)sup + pv * size, (char*)sup + l * size) > 0)
  36. {
  37. l++;
  38. continue;
  39. }
  40.  
  41. swap((char*)sup + l * size, (char*)sup + h * size);
  42. l++, h--;
  43. }
  44.  
  45. Qsort(sup, l, size, cmp, swap);
  46. Qsort((char*)sup + l * size, n - l, size, cmp, swap);
  47. }
  48.  
  49. int cmp(const void *c1, const void *c2)
  50. {
  51. int a = *(const int*)c1;
  52. int b = *(const int*)c2;
  53. if (a > b) return 1;
  54. if (a < b) return -1;
  55. return 0;
  56. }
  57.  
  58. void swap(void *c1, void *c2)
  59. {
  60. int c = *(int*)c1;
  61. *(int*)c1 = *(int*)c2;
  62. *(int*)c2 = c;
  63. }
  64.  
  65. void print(int* arr, int size)
  66. {
  67. int i = 0;
  68. for(; i < size; ++i)
  69. {
  70. printf("%d \t", arr[i]);
  71. }
  72. }
  73.  
  74. int main(void)
  75. {
  76. int arr[4] = {3,4,1,2};
  77. print(arr, 4);
  78. printf("\n\n");
  79. Qsort(arr, 4, sizeof(arr[0]), &cmp, &swap);
  80. print(arr, 4);
  81. return 0;
  82. }
  83.  
Success #stdin #stdout 0s 1788KB
stdin
Standard input is empty
stdout
3 	4 	1 	2 	

1 	2 	3 	4