diff --git a/pt/Makefile b/pt/Makefile index c83ec5f9..e833399d 100644 --- a/pt/Makefile +++ b/pt/Makefile @@ -3,7 +3,7 @@ CC ?= "${CC}" -g -Wall CFLAGS += -DMAINLINE -I./ -BIN = cpl branch psb nonroot_test negative_test +BIN = cpl branch psb nonroot_test negative_test sort_test LFLAGS = -L./ -lipt @@ -25,5 +25,8 @@ nonroot_test: negative_test: $(CC) -o $@ $@.c utils.c ${CFLAGS} ${LFLAGS} +sort_test: + $(CC) -o $@ $@.c utils.c ${CFLAGS} ${LFLAGS} + clean: rm -rf $(BIN) *.o diff --git a/pt/sort_test.c b/pt/sort_test.c new file mode 100644 index 00000000..962e0dc5 --- /dev/null +++ b/pt/sort_test.c @@ -0,0 +1,74 @@ +#include +#include +#include + +#define ARRAY_LEN 3000 + +size_t partition(int *a, size_t low, size_t high); // Move the declaration of the partition function here + +static inline void start(struct timeval *tm) +{ + gettimeofday(tm, NULL); +} + +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} + +static inline void stop(struct timeval *tm1, struct timeval *tm2) +{ + unsigned long long t = 1000 * (tm2->tv_sec - tm1->tv_sec) + + (tm2->tv_usec - tm1->tv_usec) / 1000; + printf("%llu ms\n", t); +} + +size_t partition(int *a, size_t low, size_t high) +{ + int pivot = a[high]; + size_t i = low - 1; + + for (size_t j = low; j <= high - 1; j++) + { + if (a[j] < pivot) + { + i++; + swap(&a[i], &a[j]); + } + } + swap(&a[i + 1], &a[high]); + return (i + 1); +} + +void quick_sort(int *a, size_t low, size_t high) +{ + if (low < high) + { + size_t pivot = partition(a, low, high); + quick_sort(a, low, pivot - 1); + quick_sort(a, pivot + 1, high); + } +} + +void sort_array() +{ + printf("Quick sorting array of %zu elements\n", ARRAY_LEN); + int data[ARRAY_LEN]; + for (size_t i = 0; i < ARRAY_LEN; ++i) + { + data[i] = rand(); + } + quick_sort(data, 0, ARRAY_LEN - 1); +} + +int main() +{ + struct timeval tm1, tm2; + start(&tm1); + sort_array(); + gettimeofday(&tm2, NULL); + stop(&tm1, &tm2); + return 0; +}