Created
January 26, 2020 00:01
-
-
Save BrooklinJazz/c778af67e5e95a20a05d0e4234a4fe5a to your computer and use it in GitHub Desktop.
a documented merge example in c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| void merge(int arr[], int startIndex, int endIndex) | |
| { | |
| // 1. calculate the middle index | |
| int midIndex = startIndex + ((endIndex - startIndex) / 2); | |
| // 2. determine left array size | |
| int leftArrSize = midIndex - startIndex + 1; | |
| // 3. determine right array size | |
| int rightArrSize = endIndex - midIndex; | |
| // 4. initialize left and right arrays | |
| int leftArr[leftArrSize]; | |
| int rightArr[rightArrSize]; | |
| // 5. copy values from the original array into the right and left arrays | |
| for (int i = 0; i < leftArrSize; i++) | |
| { | |
| leftArr[i] = arr[startIndex + i]; | |
| } | |
| for (int i = 0; i < rightArrSize; i++) | |
| { | |
| rightArr[i] = arr[midIndex + 1 + i]; | |
| } | |
| // 6. create our crawlers | |
| int leftCrawler = 0; | |
| int rightCrawler = 0; | |
| int resultCrawler = startIndex; | |
| // 7. crawls over these arrays mutating the original array with the smaller value | |
| // until either the left or right array is empty. | |
| while (leftCrawler < leftArrSize && rightCrawler < rightArrSize) | |
| { | |
| if (leftArr[leftCrawler] < rightArr[rightCrawler]) | |
| { | |
| arr[resultCrawler] = leftArr[leftCrawler]; | |
| leftCrawler++; | |
| } | |
| else | |
| { | |
| arr[resultCrawler] = rightArr[rightCrawler]; | |
| rightCrawler++; | |
| } | |
| resultCrawler++; | |
| } | |
| // 8. insert the remaining elements of the left or right array into the result. | |
| while (leftCrawler < leftArrSize) | |
| { | |
| arr[resultCrawler] = leftArr[leftCrawler]; | |
| resultCrawler++; | |
| leftCrawler++; | |
| } | |
| while (rightCrawler < rightArrSize) | |
| { | |
| arr[resultCrawler] = rightArr[rightCrawler]; | |
| resultCrawler++; | |
| rightCrawler++; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment