Merge sortIn computer science, merge sort or mergesort is a sort algorithm for rearranging lists (or any other data structure that can only be accessed sequentially, e.g. file streams) into a specified order. \nIt is a particularly good example of the divide and conquer algorithmic paradigm. Conceptually, merge sort works as follows : If the list to be sorted is longer than one item:\n#Divide the unsorted list into two sublists of about half the size\n#Sort each of the two sublists\n#Merge the two sorted sublists back into one sorted list. Merge sort has an average and worst-case performance of O(n log(n)). This means that it often needs to make fewer comparisons than quicksort. However, the algorithm's overhead is slightly higher than quicksort's, and, depending on the data structure to be sorted, may take more memory (though this is becoming less and less of a consideration for commonly available hardware and typical data). It is also much more efficient than quicksort if the data to be sorted can only be efficiently accessed sequentially, and is thus popular in languages such as Lisp where sequentially accessed data structures are very common. Unlike quicksort, merge sort is a stable sort. Merge sort is so inherently sequential it's practical to run it using slow tape drives as input and output devices. It requires very little memory, and the memory required does not change with the number of data elements. \nIf you have four tape drives, it works as follows:
void merge_sort(float [], int, int);\nvoid merge (float [], int, int, int);
/* sort the (sub)array v from start to end */
void merge_sort (float v[], int start, int end) {\n int middle; /* the middle of the subarray */
/* no elements to sort */\n if (start == end) return;
/* one element; already sorted! */\n if (start == end - 1) return;
/* find the middle of the array, splitting it into two subarrays */\n middle = (start + end) / 2;
/* sort the subarray from start..middle */\n merge_sort (v, start, middle);
/* sort the subarray from middle..end */\n merge_sort (v, middle, end);
/* merge the two sorted halves */\n merge (v, start, middle, end);\n}
/* merge the subarray v[start..middle] with v[middle..end], placing the\n * result back into v.\n */\nvoid merge (float v[], int start, int middle, int end) {\n int v1_n, v2_n, v1_index, v2_index, i;
/* number of elements in first subarray */\n v1_n = middle - start;
/* number of elements in second subarray */\n v2_n = end - middle;
/* create v1 and v2 subarrays */\n float v1[v1_n];\n float v2[v2_n];
/* fill v1 and v2 with the elements of the first and second\n * subarrays, respectively\n */\n for (i=0; i |
||
"There are some experiences in life which should not be demanded twice from any man, and one of them is listening to the Brahms Requiem." - George Bernard Shaw (1856-1950) |
