SortTest.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2011 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #include "include/utils/SkRandom.h"
  8. #include "src/core/SkTSort.h"
  9. #include "tests/Test.h"
  10. #include <stdlib.h>
  11. extern "C" {
  12. static int compare_int(const void* a, const void* b) {
  13. return *(const int*)a - *(const int*)b;
  14. }
  15. }
  16. static void rand_array(SkRandom& rand, int array[], int n) {
  17. for (int j = 0; j < n; j++) {
  18. array[j] = rand.nextS() & 0xFF;
  19. }
  20. }
  21. static void check_sort(skiatest::Reporter* reporter, const char label[],
  22. const int array[], const int reference[], int n) {
  23. for (int j = 0; j < n; ++j) {
  24. if (array[j] != reference[j]) {
  25. ERRORF(reporter, "%sSort [%d] failed %d %d",
  26. label, n, array[j], reference[j]);
  27. }
  28. }
  29. }
  30. DEF_TEST(Sort, reporter) {
  31. /** An array of random numbers to be sorted. */
  32. int randomArray[500];
  33. /** The reference sort of the random numbers. */
  34. int sortedArray[SK_ARRAY_COUNT(randomArray)];
  35. /** The random numbers are copied into this array, sorted by an SkSort,
  36. then this array is compared against the reference sort. */
  37. int workingArray[SK_ARRAY_COUNT(randomArray)];
  38. SkRandom rand;
  39. for (int i = 0; i < 10000; i++) {
  40. int count = rand.nextRangeU(1, SK_ARRAY_COUNT(randomArray));
  41. rand_array(rand, randomArray, count);
  42. // Use qsort as the reference sort.
  43. memcpy(sortedArray, randomArray, sizeof(randomArray));
  44. qsort(sortedArray, count, sizeof(sortedArray[0]), compare_int);
  45. memcpy(workingArray, randomArray, sizeof(randomArray));
  46. SkTHeapSort<int>(workingArray, count);
  47. check_sort(reporter, "Heap", workingArray, sortedArray, count);
  48. memcpy(workingArray, randomArray, sizeof(randomArray));
  49. SkTQSort<int>(workingArray, workingArray + count - 1);
  50. check_sort(reporter, "Quick", workingArray, sortedArray, count);
  51. }
  52. }
  53. // need tests for SkStrSearch