Docsity

Merge Sort Algorithm: Implementation and Complexity, Slides of Data Structures and Algorithms

Partial preview of the text

Download Merge Sort Algorithm: Implementation and Complexity and more Slides Data Structures and Algorithms in PDF only on Docsity!

[25] [57]^ [48]^ [37]^ [12]^ [92]^ [86]^ [33]

[25 57]^ [37^ 48]^ [12^ 92]^ [33^ 86]

[25^37 48 57]^ [12^33 86 92]

[12^25 33 37 48 57 86 92]

void mergesort (int x[ ], int n) { int aux[n], I, j, k, l1, l2, size, u1, u2; size = 1; /* Merge files of size 1 / while (size < n) { l1 = 0; / Initialize lower bounds of first file / k = 0; / k is index for auxiliary array / while (l1 + size < n ) { / Check to see if there are 2 files to merge. Compute remaining indices */

l2 = l1 + size; u1 = l2 – 1; u2 = (l2 + size -1 < n)? l2 + size -1 : n-1; /* Proceed through the two subfiles / for ( i = l1, j = l2; i<=u1&&j<=u2; k++) / Enter smaller into the array aux */ if (x[i] <= x[j]) aux[k] = x[i++]; else aux[k] = x[ j++];

/* Copy any remaining single file / for (i = l1; k<n; i++) aux[k++] = x[ i]; / Copy aux into x and adjust size / for (i=0; i<n; i++) x[i] = aux[i]; size=2; } } The time complexity of merge sort is O(n logn).