×

# merge sort: looping variables test condition

 0 there is a for loop at the end of the function merge() wherin i<=num_elements is used. why is it <= and not just i< num_elements #include void m_sort(int numbers[], int temp[], int left, int right); void mergeSort(int numbers[], int temp[], int array_size); void merge(int numbers[], int temp[], int left, int mid, int right); void mergeSort(int numbers[], int temp[], int array_size) { m_sort(numbers, temp, 0, array_size - 1); } void m_sort(int numbers[], int temp[], int left, int right) { int mid; if (right > left) { mid = (right + left) / 2; m_sort(numbers, temp, left, mid);//this calls for sorting the left part m_sort(numbers, temp, mid+1, right);//this calls for sorting the right part,mid+1 because mid goes to the left half in the previous statement merge(numbers, temp, left, mid+1, right);//why mid+1 } } void merge(int numbers[], int temp[], int left, int mid, int right)//left middle and right of the array or left half or right half { int i, left_end, num_elements, tmp_pos;//num_elts for no._elts of array,l_e is middle postion,tmp_pos keeps track of the position of elt filling //in the temporary array,i is used in for loop that comes in the end left_end = mid - 1;//left end means the end of the left end tmp_pos = left;//tmp pos is the postion of the place being filled in the temporary array num_elements = right - left + 1; while ((left <= left_end) && (mid <= right))//compares the first elts of the two halfs and fills it into temp array { if (numbers[left] <= numbers[mid]) { temp[tmp_pos] = numbers[left]; tmp_pos = tmp_pos + 1; left = left +1; } else { temp[tmp_pos] = numbers[mid]; tmp_pos = tmp_pos + 1; mid = mid + 1; } } while (left <= left_end)//if right half used up fills the remaining slots in the temp array with the elts left in left half { temp[tmp_pos] = numbers[left]; left = left + 1; tmp_pos = tmp_pos + 1; } while (mid <= right)//same as above while loop only thing is here the operation done on the other side { temp[tmp_pos] = numbers[mid]; mid = mid + 1; tmp_pos = tmp_pos + 1; } for (i=0; i <= num_elements; i++)//copies the values from temp array to number array { numbers[right] = temp[right]; right = right - 1; } } int main(void) { int size; printf("enter the size of the array\n"); scanf("%d",&size); int a[size],t[size]; printf("enter the elements\n"); for(int i=0;i

 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×74
×28

question asked: 26 May '13, 17:41

question was seen: 2,427 times

last updated: 27 May '13, 08:08