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 8 #include "SkRandom.h" 9 #include "SkTSort.h" 10 #include "Test.h" 11 12 extern "C" { 13 static int compare_int(const void* a, const void* b) { 14 return *(const int*)a - *(const int*)b; 15 } 16 } 17 18 static void rand_array(SkRandom& rand, int array[], int n) { 19 for (int j = 0; j < n; j++) { 20 array[j] = rand.nextS() & 0xFF; 21 } 22 } 23 24 static void check_sort(skiatest::Reporter* reporter, const char label[], 25 const int array[], const int reference[], int n) { 26 for (int j = 0; j < n; ++j) { 27 if (array[j] != reference[j]) { 28 ERRORF(reporter, "%sSort [%d] failed %d %d", 29 label, n, array[j], reference[j]); 30 } 31 } 32 } 33 34 DEF_TEST(Sort, reporter) { 35 /** An array of random numbers to be sorted. */ 36 int randomArray[500]; 37 /** The reference sort of the random numbers. */ 38 int sortedArray[SK_ARRAY_COUNT(randomArray)]; 39 /** The random numbers are copied into this array, sorted by an SkSort, 40 then this array is compared against the reference sort. */ 41 int workingArray[SK_ARRAY_COUNT(randomArray)]; 42 SkRandom rand; 43 44 for (int i = 0; i < 10000; i++) { 45 int count = rand.nextRangeU(1, SK_ARRAY_COUNT(randomArray)); 46 rand_array(rand, randomArray, count); 47 48 // Use qsort as the reference sort. 49 memcpy(sortedArray, randomArray, sizeof(randomArray)); 50 qsort(sortedArray, count, sizeof(sortedArray[0]), compare_int); 51 52 memcpy(workingArray, randomArray, sizeof(randomArray)); 53 SkTHeapSort<int>(workingArray, count); 54 check_sort(reporter, "Heap", workingArray, sortedArray, count); 55 56 memcpy(workingArray, randomArray, sizeof(randomArray)); 57 SkTQSort<int>(workingArray, workingArray + count - 1); 58 check_sort(reporter, "Quick", workingArray, sortedArray, count); 59 } 60 } 61 62 // need tests for SkStrSearch 63