It's not sorting because &(*data_resource)->length - 1
evaluates to &(*data_resource)->low
.
&(*data_resource)->length
is a pointer to an int
. When you subtract 1 from it, it points to the int
just before and that happens to be &(*data_resource)->low
because you defined the structure members in precisely this order:
typedef struct Resource
{
int low;
int length;
int *data;
} Resource;
So, your sorting code gets 2 identical indices to work with and rightly does not sort anything as there's nothing to sort in a subarray consisting of just one element.
Here's a slightly modified version that works:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Resource
{
int low;
int length;
int *data;
} Resource;
void Swap(int *first, int *second)
{
int tmp = *first;
*first = *second;
*second = tmp;
}
void SortQuick(int **data, int *low, int *high)
{
int i = *low,
j = *high,
x = (*data)[(*low + *high) / 2];
do
{
while((*data)[i] < x) i++;
while((*data)[j] > x) j--;
if(i <= j)
{
Swap(&(*data)[i], &(*data)[j]);
i++;
j--;
}
} while(i <= j);
if(i < *high) SortQuick(data, &i, high);
if(*low < j) SortQuick(data, low, &j);
}
void ArrayPrint(int **data, int *array_length)
{
for(int i = 0; i < *array_length; i++)
{
printf("[%i]: %20i\r\n", i, (*data)[i]);
}
}
void ArrayInit(int **data, int *array_length)
{
(*data) = (int*)malloc(sizeof(int) * *array_length);
for(int i = 0; i < *array_length; i++)
{
(*data)[i] = rand();
}
}
int GlobalInit(Resource **data_resource)
{
srand((unsigned int)rand());
*data_resource = (Resource*)malloc(sizeof(Resource));
(*data_resource)->low = 0;
(*data_resource)->length = 10;//rand();
ArrayInit(&(*data_resource)->data, &(*data_resource)->length);
return (*data_resource)->length;
}
void BenchmarkTest(Resource **data_resource)
{
ArrayPrint(&(*data_resource)->data, &(*data_resource)->length);
(*data_resource)->length--;
SortQuick(&(*data_resource)->data, &(*data_resource)->low, &(*data_resource)->length);
(*data_resource)->length++;
ArrayPrint(&(*data_resource)->data, &(*data_resource)->length);
}
int main(void)
{
Resource *data_resource = NULL;
GlobalInit(&data_resource);
BenchmarkTest(&data_resource);
return 0;
}
Output (ideone):
[0]: 1362961854
[1]: 8891098
[2]: 392263175
[3]: 158428306
[4]: 2074436122
[5]: 47170999
[6]: 431826012
[7]: 1599373168
[8]: 1769073836
[9]: 1043058022
[0]: 8891098
[1]: 47170999
[2]: 158428306
[3]: 392263175
[4]: 431826012
[5]: 1043058022
[6]: 1362961854
[7]: 1599373168
[8]: 1769073836
[9]: 2074436122