#include void mergesort(int* array, int length); void merge(int* array, int* left, int leftlen, int* right, int rightlen); // This is a recursive divide-and-conquer sorting algorithm known to programmers // around the world as Mergesort // array - The integers to be sorted // length - The length of that array void mergesort(int* array, int length) { int* lefthalf; int* righthalf; int i; // Base case: An array with one or zero elements is already trivially sorted if(length <= 1) { return; } // Copy off the left half of the array and recursively mergesort it lefthalf = (int*)calloc(length/2, sizeof(int)); for(i = 0; i < length/2; i++) { lefthalf[i] = array[i]; } mergesort(lefthalf, length/2); // Copy off the right half of the array and recursively mergesort it righthalf = (int*)calloc(length - length/2, sizeof(int)); for(i = length/2; i= rightlen) { while(leftindex < leftlen) { array[arrayindex] = left[leftindex]; arrayindex++; leftindex++; } } // Otherwise, there are still integers in the right half, so copy those else { while(rightindex < rightlen) { array[arrayindex] = right[rightindex]; arrayindex++; rightindex++; } } } int main(void) { int array[] = {3, 5, 2, 4, 1, 7, 6, 9, 8}; int i=0; // Output the array before it's sorted for(i=0;i<9;i++) printf("%d ",array[i]); printf("\n"); // Sort the array mergesort(array, 9); // Output the array after it's sorted for(i=0;i<9;i++) printf("%d ",array[i]); printf("\n"); system("PAUSE"); }