testqsort.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any damages
  5. arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it
  8. freely.
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include "SDL.h"
  13. static int
  14. num_compare(const void *_a, const void *_b)
  15. {
  16. const int a = *((const int *) _a);
  17. const int b = *((const int *) _b);
  18. return (a < b) ? -1 : ((a > b) ? 1 : 0);
  19. }
  20. static void
  21. test_sort(const char *desc, int *nums, const int arraylen)
  22. {
  23. int i;
  24. int prev;
  25. SDL_Log("test: %s arraylen=%d", desc, arraylen);
  26. SDL_qsort(nums, arraylen, sizeof (nums[0]), num_compare);
  27. prev = nums[0];
  28. for (i = 1; i < arraylen; i++) {
  29. const int val = nums[i];
  30. if (val < prev) {
  31. SDL_Log("sort is broken!");
  32. return;
  33. }
  34. prev = val;
  35. }
  36. }
  37. int
  38. main(int argc, char *argv[])
  39. {
  40. static int nums[1024 * 100];
  41. static const int itervals[] = { SDL_arraysize(nums), 12 };
  42. int iteration;
  43. for (iteration = 0; iteration < SDL_arraysize(itervals); iteration++) {
  44. const int arraylen = itervals[iteration];
  45. int i;
  46. for (i = 0; i < arraylen; i++) {
  47. nums[i] = i;
  48. }
  49. test_sort("already sorted", nums, arraylen);
  50. for (i = 0; i < arraylen; i++) {
  51. nums[i] = i;
  52. }
  53. nums[arraylen-1] = -1;
  54. test_sort("already sorted except last element", nums, arraylen);
  55. for (i = 0; i < arraylen; i++) {
  56. nums[i] = (arraylen-1) - i;
  57. }
  58. test_sort("reverse sorted", nums, arraylen);
  59. for (i = 0; i < arraylen; i++) {
  60. nums[i] = random();
  61. }
  62. test_sort("random sorted", nums, arraylen);
  63. }
  64. return 0;
  65. }
  66. /* vi: set ts=4 sw=4 expandtab: */