Advertisement
Guest User

Untitled

a guest
Jun 25th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "string.h"
  4.  
  5. /* run this program using the console pauser or add your own getch, system("pause") or input loop */
  6.  
  7.  
  8. void swap_str_ptrs(char const **arg1, char const **arg2)
  9. {
  10. const char *tmp = *arg1;
  11. *arg1 = *arg2;
  12. *arg2 = tmp;
  13. }
  14.  
  15. void print_list(char const *args[], unsigned len)
  16. {
  17. unsigned i=0;
  18. for (;i<len;++i)
  19. puts(args[i]);
  20. }
  21.  
  22.  
  23. void quicksort_strs(char const *args[], unsigned int len)
  24. {
  25. // holds our non-recursive stack of segments
  26. struct segment
  27. {
  28. char const **arr;
  29. unsigned int len;
  30. struct segment* next;
  31. } *stack = NULL;
  32.  
  33. stack = malloc(sizeof(*stack));
  34. stack->arr = args;
  35. stack->len = len;
  36. stack->next = NULL;
  37.  
  38. while (stack != NULL)
  39. {
  40. unsigned int i, pvt=0;
  41. struct segment *tmp = stack;
  42. stack = stack->next;
  43.  
  44. // pull values and delete segment record
  45. args = tmp->arr;
  46. len = tmp->len;
  47. free(tmp);
  48.  
  49. // nothing to unary segments
  50. if (len <= 1)
  51. continue;
  52.  
  53. // swap a randomly selected value to the last node
  54. swap_str_ptrs(args+((unsigned int)rand() % len), args+len-1);
  55.  
  56. // reset the pivot index to zero, then scan
  57. for (i=0;i<len-1;++i)
  58. {
  59. if (strcmp(args[i], args[len-1]) < 0)
  60. swap_str_ptrs(args+i, args+pvt++);
  61. }
  62. // move the pivot value into its place
  63. swap_str_ptrs(args+pvt, args+len-1);
  64.  
  65. // lhs segment push
  66. if (pvt > 1)
  67. {
  68. tmp = malloc(sizeof(*tmp));
  69. tmp->arr = args;
  70. tmp->len = pvt;
  71. tmp->next = stack;
  72. stack = tmp;
  73. }
  74. // rhs segment push
  75. if ((len - ++pvt) > 1)
  76. {
  77. tmp = malloc(sizeof(*tmp));
  78. tmp->arr = args+pvt;
  79. tmp->len = len-pvt;
  80. tmp->next = stack;
  81. stack = tmp;
  82. }
  83. }
  84. }
  85.  
  86. int main()
  87. {
  88. char const *args[] =
  89. {
  90. "this", "is", "a", "test", "of", "quicksort", "with", "strings"
  91. };
  92.  
  93. srand((unsigned)time(NULL));
  94. quicksort_strs(args, sizeof(args)/sizeof(*args));
  95. print_list(args, sizeof(args)/sizeof(*args));
  96. return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement