@@ -16,6 +16,8 @@ in the source distribution for its full text.
1616#include "XUtils.h"
1717
1818
19+ static Object_Compare vectorCompareFn ;
20+
1921Vector * Vector_new (const ObjectClass * type , bool owner , int size ) {
2022 Vector * this ;
2123
@@ -95,39 +97,14 @@ void Vector_prune(Vector* this) {
9597
9698//static int comparisons = 0;
9799
98- static void swap (Object * * array , int indexA , int indexB ) {
100+ static inline void swap (Object * * array , int indexA , int indexB ) {
99101 assert (indexA >= 0 );
100102 assert (indexB >= 0 );
101103 Object * tmp = array [indexA ];
102104 array [indexA ] = array [indexB ];
103105 array [indexB ] = tmp ;
104106}
105107
106- static int partition (Object * * array , int left , int right , int pivotIndex , Object_Compare compare ) {
107- const Object * pivotValue = array [pivotIndex ];
108- swap (array , pivotIndex , right );
109- int storeIndex = left ;
110- for (int i = left ; i < right ; i ++ ) {
111- //comparisons++;
112- if (compare (array [i ], pivotValue ) <= 0 ) {
113- swap (array , i , storeIndex );
114- storeIndex ++ ;
115- }
116- }
117- swap (array , storeIndex , right );
118- return storeIndex ;
119- }
120-
121- static void quickSort (Object * * array , int left , int right , Object_Compare compare ) {
122- if (left >= right )
123- return ;
124-
125- int pivotIndex = (left + right ) / 2 ;
126- int pivotNewIndex = partition (array , left , right , pivotIndex , compare );
127- quickSort (array , left , pivotNewIndex - 1 , compare );
128- quickSort (array , pivotNewIndex + 1 , right , compare );
129- }
130-
131108// If I were to use only one sorting algorithm for both cases, it would probably be this one:
132109/*
133110
@@ -167,10 +144,15 @@ static void insertionSort(Object** array, int left, int right, Object_Compare co
167144 }
168145}
169146
147+ static int Vector_compareObjects (const void * v1 , const void * v2 ) {
148+ return vectorCompareFn (* (const Object * const * )v1 , * (const Object * const * )v2 );
149+ }
150+
170151void Vector_quickSortCustomCompare (Vector * this , Object_Compare compare ) {
171152 assert (compare );
172153 assert (Vector_isConsistent (this ));
173- quickSort (this -> array , 0 , this -> items - 1 , compare );
154+ vectorCompareFn = compare ;
155+ qsort (this -> array , this -> items , sizeof (Object * ), Vector_compareObjects );
174156 assert (Vector_isConsistent (this ));
175157}
176158
0 commit comments