File System Assignment

Copyright Tristan Aubrey-Jones and Dale Caffull December 2006.

sort_test.c

home Home   up Up   ( Download )


#include #include typedef unsigned char BYTE; typedef unsigned short int LBA; struct BLOCK_TRANSFER { LBA lba; BYTE *data; unsigned short length; }; struct BLOCK_RANGE { LBA start; unsigned short length; }; void sort_swap(struct BLOCK_TRANSFER arr[], int a, int b) { /* swap values */ struct BLOCK_TRANSFER v = arr[a]; arr[a] = arr[b]; arr[b] = v; } int sort_partition(struct BLOCK_TRANSFER arr[], int left, int right, int pivotIndex) { int i; int storeIndex; /* get pivot value */ LBA pivotValue = arr[pivotIndex].lba; /* move pivot to end */ sort_swap(arr, pivotIndex, right); /* swap values on either side of pivot */ storeIndex = left; for(i = left; i < right; i++) { if (arr[i].lba <= pivotValue) { /* swap */ sort_swap(arr, storeIndex, i); storeIndex++; } } /* move pivot to final place */ sort_swap(arr, right, storeIndex); return storeIndex; } void sort_recursive(struct BLOCK_TRANSFER arr[], int left, int right) { /* perform quicksort on the two halves of the array */ if (right > left) { int pivotIndex = left + ((right - left) / 2); int pivotNewIndex = sort_partition(arr, left, right, pivotIndex); sort_recursive(arr, left, pivotNewIndex - 1); sort_recursive(arr, pivotNewIndex+1, right); } } void sort(struct BLOCK_TRANSFER arr[], int length) { /* quicksort values */ sort_recursive(arr, 0, length-1); } void printarray(struct BLOCK_TRANSFER arr[], int left, int right) { for (; left <= right; left++) { printf("%i\n", arr[left].lba); } } int main(int argc, char *argv[]) { int i; struct BLOCK_TRANSFER blocks[10]; for (i = 0; i < 10; i++) { blocks[i].lba = (LBA)(10 - i); blocks[i].data = 0; } printarray(blocks, 0, 9); sort(blocks, 10); printf("\n"); printarray(blocks, 0, 9); system("PAUSE"); return 0; }