I write a program about merge sort. I have some problem with array things.
The first line represents the amount of the input series. (Now i input 2, means have 2 input)
Input: 2
9,5,6,7,1,8,3
22,86,-5,8,66,9
Output:
1 3 5 6 7 8 9
-5 1 3 5 6 7 8 8 9 9 22 66 86
How did i on the next second output the array no have the first input value 9,5,6,7,1,8,3 only have this second input 22,86,-5,8,66,9
Means that the output should be like
1 3 5 6 7 8 9
-5 8 9 22 66 86
Here's my code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int limit,i;
//char *tree_input = malloc(1000*sizeof(char));
//int *array1 = malloc(1000 * sizeof(int));
char tree_input[1000];
int array1[1000]; //char also can?
int j=0;
char *pch;
printf("input the limit\n");
scanf("%d",&limit);
for(i=0; i<limit; i++)
{
scanf("%s",tree_input);
pch = strtok(tree_input, ",");
while(pch!=NULL)
{
//printf("%s\n",pch);
array1[j]=atoi(pch); //atoi it
j++;
pch = strtok (NULL, ",");
}
mergeSort(array1, 0, j - 1);
printArray(array1, j);
}
return 0;
}
You need to reset the j after processing each input.
Otherwise your array1 will have all the inputs.
for(i=0; i<limit; i++)
{
scanf("%s",tree_input);
pch = strtok(tree_input, ",");
while(pch!=NULL)
{
//printf("%s\n",pch);
array1[j]=atoi(pch); //atoi it
j++;
pch = strtok (NULL, ",");
}
mergeSort(array1, 0, j - 1);
printArray(array1, j);
j=0; //Reset the j
}
Related
This is a C program that i wrote to achieve the following purpose.
User needs to provide an integer array A of size N and an integer K ,
where the program needs to rotate the array in the right direction by
K steps and then print the resultant array.
Input Format:
The first line will consists of one integer T denoting the number of
test cases. For each test case: The first line consists of two
integers N and K, N being the number of elements in the array and K
denotes the number of steps of rotation. The next line consists of N
space separated integers , denoting the elements of the array A.
Output Format:
Print the array after rotation in the single line for each test case.
These are sample input and output
This is the code that i wrote to achieve the purpose,
#include<stdio.h>
int main()
{ int i,n,a[100],temp,shiftlimit,cyclelimit;
int shiftcount = 0;
int cyclcount = 0;
scanf("%d",&cyclelimit);
while(cyclcount != cyclelimit){
scanf("%d",&n);
scanf("%d",&shiftlimit);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}while(shiftcount != shiftlimit){
temp=a[n-1];
for(i=n-1;i>0;i--)
{
a[i]=a[i-1];
}
a[0]=temp;
shiftcount += 1;}
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
printf("\n");cyclcount +=1;}
}
And there are some complexity parameter as follows:
Complexity parameters
This code works fine when T= cyclelimit (line 7) is 1 but as soon as user enters 2 or more the code starts to malfunction.
I have use while loop to achieve the purpose but it is not working after 1 loop.
My output:
My output
Required Ouput:
Expected output
1., Use functions - do not program in main.
2. Use standard functions.
int *allocateArr(size_t N)
{
int *arr = malloc(sizeof(*arr) * N);
return arr;
}
int *rotateLeft(int *arr, size_t N, size_t K)
{
int *temp = malloc(sizeof(*temp) * K); /* check for errors*/
for(size_t i = 0; i < K; i ++) temp[i] = arr[i];
for(size_t i = 0; i < N - K; i ++) arr[i] = arr[K + i];
for(size_t i = 0; i < K; i ++) arr[i + (N - K)] = temp[i];
free(temp);
return arr;
}
int *rotateRight(int *arr, size_t N, size_t K)
{
return rotateLeft(arr, N, N - K);
}
#define SIZE 10
int main(void)
{
int *arr = allocateArr(SIZE); /* check for errors*/
for(size_t i = 1; i <= SIZE; i++) arr[i - 1] = i;
for(size_t i = 0; i < SIZE; i++) printf("%d ",arr[i]);
printf("\n");
rotateRight(arr, SIZE, 4);
for(size_t i = 0; i < SIZE; i++) printf("%d ",arr[i]);
printf("\n");
for(size_t i = 1; i <= SIZE; i++) arr[i - 1] = i;
rotateLeft(arr, SIZE, 4);
for(size_t i = 0; i < SIZE; i++) printf("%d ",arr[i]);
printf("\n");
free(arr);
}
int *allocateArr(size_t N)
{
int *arr = malloc(sizeof(*arr) * N);
return arr;
}
int *rotateLeft(int *arr, size_t N, size_t K)
{
int *temp = malloc(sizeof(*temp) * K); /* check for errors*/
memcpy(temp, arr, sizeof(*arr) * K);
memmove(arr, arr + K, sizeof(*arr) * (N - K));
memcpy(arr + (N - K), temp, sizeof(*arr) * K);
free(temp);
return arr;
}
int *rotateRight(int *arr, size_t N, size_t K)
{
int *temp = malloc(sizeof(*temp) * K); /* check for errors*/
memcpy(temp, arr + (N - K), sizeof(*arr) * K);
memmove(arr + K, arr, sizeof(*arr) * (N - K));
memcpy(arr, temp, sizeof(*arr) * K);
free(temp);
return arr;
}
#define SIZE 10
int main(void)
{
int *arr = allocateArr(SIZE); /* check for errors*/
for(size_t i = 1; i <= SIZE; i++) arr[i - 1] = i;
for(size_t i = 0; i < SIZE; i++) printf("%d ",arr[i]);
printf("\n");
rotateRight(arr, SIZE, 4);
for(size_t i = 0; i < SIZE; i++) printf("%d ",arr[i]);
printf("\n");
for(size_t i = 1; i <= SIZE; i++) arr[i - 1] = i;
rotateLeft(arr, SIZE, 4);
for(size_t i = 0; i < SIZE; i++) printf("%d ",arr[i]);
printf("\n");
free(arr);
}
Result:
1 2 3 4 5 6 7 8 9 10
7 8 9 10 1 2 3 4 5 6
5 6 7 8 9 10 1 2 3 4
I'm new to programming,I'm trying to implement a merge sort function into my program, but it's not working correctly. I went over and over the code but I can't find the problem.
If for example the user input for a 6 element array is : 3 2 4 1 6 7
The output is: 1 3 2 4 32708 32708
Can someone help me? Also, if anyone have any advice for improving my coding style would be much appreciated.Thanks.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a, n;
a = malloc(100 * sizeof(int)); // dynamically allocating memory for original array
if (a == NULL)
return 1;
printf("Enter n of elements in the array:");
scanf("%i", &n); // n of elements the in array
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%i", &a[i]); // prompt user for input elements
}
int f, l, m, n1, n2; // declaring variables
f = 0; // first element
l = n - 1; // last element
m = (f + l) / 2; // mid point
n1 = m + 1 - f; // n elements l1
n2 = l - m; // n elements l2
int l1[n1]; // temp array 1
int l2[n2]; // temp array2
for (int i = 0; i < n1; i++) {
l1[i] = a[i]; // copy elements into temp l1
}
for (int j = 0; j < n2; j++) {
l2[j] = a[m + 1 + j]; // copy elements into temp l2
}
int i, j, k; // variable for arrays index
i = 0;
j = 0;
k = 0;
//sorting and copying elements in original array
while (i < n1 && j < n2) {
if (l1[i] <= l2[j]) { // if element l1 smaller or equal to l2 element
a[k] = l1[i]; // copy element l1 into original array
i++; // increment l1
} else { // if element l1 bigger than l2
a[k] = l2[j]; // copy element l2 into original array
j++; // increment l2
}
k++; // increment original array
}
// copy remaining elements (if any)
while (i < n1) {
a[k] = l1[i];
i++;
k++;
}
while (j < n2) {
a[k] = l2[i];
j++;
k++;
}
printf("Your sorted array:\n");
for (int d = 0; d < n; d++) {
printf("%i ", a[d]); // print sorted array
}
printf("\n");
free(a); // freeing original array
}
You need to merge recursively. You wrote only the merge part and not the recursive sort function.
More info: https://www.geeksforgeeks.org/merge-sort/
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there are any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there are any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main(void)
{
int *a, n;
printf("Enter n of elements in the array:");
scanf("%i", &n); //n of elements the in array
a = malloc(n * sizeof(int)); //dynamically allocating memory for original array
if (a == NULL)
return 1;
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%i", &a[i]); //prompt user for input elements
}
mergeSort(a, 0, n - 1);
printf("Your sorted array:\n");
for (int d = 0; d < n; d++) {
printf("%i ", a[d]); //print sorted array
}
printf("\n");
free(a); //freeing original array
return 0;
}
I have to test Mergesort with different sizes of data. The problem I encounter is that if the array of ints is around the size of 5000000 my code is crashing but without giving an error. I calculated the amount of space the array would take and if I'm not wrong this would be about 0,02 GB and my RAM is 8GB. I also searched if there is a max size for an array and didnt find anything useful. So where is the problem?
/* C program for Merge Sort */
#include<stdlib.h>
#include<stdio.h>
#include <time.h>
#define MAX 2000000
int arr[MAX];
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(l, m);
mergeSort(m+1, r);
merge(l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray()
{
int i;
for (i=0; i < MAX; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Driver program to test above functions */
int main()
{
srand(time(NULL));
for (int var = 0; var < MAX; ++var) {
arr[var] = rand() % 100;
}
clock_t t1, t2;
//printf("Given array is \n");
// printArray();
t1 = clock();
mergeSort(0, MAX - 1);
t2 = clock();
printf("\nSorted array is \n");
printArray();
float timetaken = t2 - t1;
timetaken /= CLOCKS_PER_SEC;
printf("Time spend: %f\n", timetaken);
return 0;
}
in
void merge(int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
...
Probably L and R are too large to be placed in the stack, the size of the stack is limited, do ulimit-a to see the limit.
If this is the reason you will have to allocate them in the heap (malloc), and don't forget after to free them ;-)
When you need a big array whose size if a constant (this is not the case here) and the function using it is not directly nor indirectly recursive, you can use a static var, I mean for example : void foo() { ... static int v[4096]; ... } rather than void foo() { ... int v[4096]; ... }
This is what I have so far
https://notepad.vn/lvqrsmz99
#include<stdlib.h>
#include<stdio.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[20];
int i,n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printArray(arr, n);
mergeSort(arr, 0, n - 1);
printf("\nSorted array is \n");
printArray(arr, n);
return 0;
}
This is what I need to print prior the final sorted array:
3
14
3 14
1
12
5
1 3 14
5 12
Noobie, there is a pretty good hint about where the "merge" is taking place in your code. That would provide a perfect place to look at the left and right sub-arrays before the merge.
If you look at the merge() function, you see the left and right sub-arrays being populated in the following code:
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
With a little creativity, you could output the sub-arrays as they are being filled to obtain your desired output, e.g.
for (i = 0; i < n1; i++) {
L[i] = arr[l + i];
printf (" %d", L[i]);
}
putchar ('\n');
for (j = 0; j < n2; j++) {
R[j] = arr[m + 1 + j];
printf (" %d", R[j]);
}
putchar ('\n');
(you could even add an additional putchar ('\n'); after your first call to printArray (arr, n); to format the output a bit nicer)
Example Use/Output
When implemented, your output would be:
$ echo "5 3 14 1 12 5" | ./bin/mergeprn
3 14 1 12 5
3
14
3 14
1
12
5
1 3 14
5 12
Sorted array is
1 3 5 12 14
(the input values were gleaned from your question)
Other Issues
Don't use magic numbers in your code (except where absolutely required like with the scanf field-width modifier). Instead, If you need a constant, #define one (or more), or use a global enum to do the same thing. That way you have one single place at the top of your code to change things if needed and you don't have to go picking through your declarations or loop limits to change things. E.g.
#define MAXA 20
...
int arr[MAXA] = {0}; /* always initialize arrays */
Always Validate scanf Return
Any time you are using scanf you must validate the return or you are just asking for Undefined Behavior in the event of a matching or input failure. It doesn't take much more effort, but will save you a world of grief, e.g.
if (scanf ("%d", &n) != 1) {
fputs ("error: invalid array size\n", stderr);
return 1;
}
if (n > MAXA) { /* protect your array bounds */
fprintf (stderr, "error: array size exceeds bound '%d'\n", MAXA);
return 1;
}
if (n < 2) { /* make sure you have something to sort */
fputs ("error, 'n' less than 2, nothing to sort\n", stderr);
return 1;
}
for (i = 0; i < n; i++)
if (scanf ("%d", &arr[i]) != 1) {
fprintf (stderr, "error: invalid input 'arr[%d]'\n", i);
return 1;
}
Now you can rest assured you are processing valid input, and not some accidental character that causes a matching failure and Undefined Behavior in your code.
I have been going through Introduction to Algorithms, and have been trying to implement the MERGE-SORT algorithm in C programming language to gain a better understanding of it.
The book presents two pseudo-codes:
and
While I do understand the above procedures, I must be missing something during the implementation.
I must be missing something from the pseudo-code but cannot figure it out yet. Any suggestions as to why this is happening would be appreciated.
EDIT: Updated Code and Output
/* C program for Merge Sort */
#include<stdlib.h>
#include<stdio.h>
void MERGE(int [], int , int , int );
void printArray(int [], int );
void MERGE_SORT(int [], int , int );
int main(void)
{
int A[] = { 12, 11, 13, 5, 6, 7, 2, 9 };
int arr_size = sizeof(A) / sizeof(A[0]);
printf("Given array is \n");
printArray(A, arr_size);
MERGE_SORT(A, 0, arr_size); //Fixed: Index to start from zero
printf("\nSorted array is \n");
printArray(A, arr_size);
return 0;
}
void MERGE(int A[], int p, int q, int r)
{
int i = 0;
int j = 0;
int n1 = q - p + 1; //Computing length of sub-array 1
int n2 = r - q; //Computing length of sub-array 2
int *L = malloc((n1 + 2) * sizeof(*L + 1)); //Creating Left array
int *R = malloc((n2 + 2) * sizeof(*R + 1)); //Creating Right array
for (int i = 0; i <= n1; i++) { //Fixed: <=, i start from 0
L[i] = A[p + i - 1];
}
for (int j = 0; j <= n2; j++) { //Fixed: <=, i start from 0
R[j] = A[q + j];
}
L[n1 + 1] = 99; //Placing Sentinel at the end of array
R[n2 + 1] = 99;
i = 1;
j = 1;
/*Prior to the first iteration k = p, so the subarray is empty.
Both L[i] and R[j] are the smallest elements of their arrays and have not
been copied back to A*/
for (int k = p; k <= r; k++) { //Fixed: <=
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
}
else { //Fixed: Assignment and not condition check for A[k]
A[k] = R[j];
j++;
}
}
free(L);
free(R);
}
void MERGE_SORT(int A[], int p, int r)
{
//During first iteration p = 1 & r = 8
if (p < r) {
int q = (p + r) / 2;
MERGE_SORT(A, p, q);
MERGE_SORT(A, q + 1, r);
MERGE(A, p, q, r);
}
}
/* Function to print an array */
void printArray(int Arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", Arr[i]);
printf("\n");
}
Looked in the pseudo code and found out that some things have been mistakenly written wrong.
1. You need to be careful with the array index to start from 0 or 1
2. Merge last part in for loop is actually an assignment instead for conditional check.
Edit: Have updated the code to fix for the error Stack around the variable A was corrupted
Please find the corrected code here(Lookout for //Fixed for fixes)
/* C program for Merge Sort */
#include<stdlib.h>
#include<stdio.h>
void MERGE(A, p, q, r);
void printArray(Arr, size);
void MERGE_SORT(A, p, r);
int main(void)
{
int A[] = { 12, 11, 13, 5, 6, 7, 2, 9 };
int arr_size = sizeof(A) / sizeof(A[0]);
printf("Given array is \n");
printArray(A, arr_size);
MERGE_SORT(A, 0, arr_size - 1); //Fixed: Index to start from zero, arr_size - 1
printf("\nSorted array is \n");
printArray(A, arr_size);
return 0;
}
void MERGE(int A[], int p, int q, int r)
{
int i = 0;
int j = 0;
int n1 = q - p + 1; //Computing length of sub-array 1
int n2 = r - q; //Computing length of sub-array 2
int *L = malloc((n1+1) * sizeof(*L+1)); //Creating Left array
int *R = malloc((n2+1) * sizeof(*R+1)); //Creating Right array
for (int i = 0; i < n1; i++) { //Fixed: i start from 0
L[i] = A[p + i];
}
// int arr_size = sizeof(A) / sizeof(A[0]);
for (int j = 0; j < n2; j++) { //Fixed: j start from 0
R[j] = A[q + j + 1];
}
L[n1] = 99; //Placing Sentinel at the end of array
R[n2] = 99;
i = 0; //Fixed: i and j to start from 0
j = 0;
/*Prior to the first iteration k = p, so the subarray is empty.
Both L[i] and R[j] are the smallest elements of their arrays and have not
been copied back to A*/
for (int k = p; k <= r; k++) { //Fixed: <=
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
}
else { //Fixed: Assignment and not condition check for A[k]
A[k] = R[j];
j++;
}
}
free(L);
free(R);
}
void MERGE_SORT(int A[], int p, int r)
{
//During first iteration p = 1 & r = 8
if (p < r) {
int q = (p + r) / 2;
MERGE_SORT(A, p, q);
MERGE_SORT(A, q + 1, r);
MERGE(A, p, q, r);
}
}
/* Function to print an array */
void printArray(int Arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", Arr[i]);
printf("\n", size);
}
Hope it helps.
Revert for any doubts.
here are some changes i have done to your code `
#include<stdlib.h>
#include<stdio.h>
void MERGE(int *A,int p,int q,int r);
void printArray(int *Arr,int size);
void MERGE_SORT(int *A,int p,int r);
int main(void){
int A[] = { 12, 11, 13, 5, 6, 7, 2, 9 };
int arr_size = sizeof(A) / sizeof(A[0]);
printf("Given array is \n");
printArray(A, arr_size);
MERGE_SORT(A, 0, arr_size -1); // pass the indices of the array
printf("\nSorted array is \n");
printArray(A, arr_size);
return 0;
}
void MERGE(int A[], int p, int q, int r){
int i = 0;
int j = 0;
int k; //declair it here
int n1 = q - p + 1; //Computing length of sub-array 1
int n2 = r - q; //Computing length of sub-array 2
int *L = malloc((n1) * sizeof(*L+1)); //Creating Left array
int *R = malloc((n2) * sizeof(*R+1)); //Creating Right array
for (int i = 0; i < n1; i++) { //start coping from zero
L[i] = A[p + i];
}
for (int j = 0; j < n2; j++) {
R[j] = A[q +1 + j];
}
// L[n1] = 99; we won't be needing these as to mark the end we already know the size of arrays
// R[n2] = 99;
// i = 1;
// j = 1;
/*Prior to the first iteration k = p, so the subarray is empty.
Both L[i] and R[j] are the smallest elements of their arrays and have not
been copied back to A*/
for (k = p; k < r+1 && i < n1 && j<n2; k++) {
//i & j checks weather the array has completed or not
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
}
else {
A[k]=R[j];
j++;
}
}
// when one of the array is empty u can copy the rest of the array with out compairing
while(i<n1)
A[k++]=L[i++];
while(j<n2)
A[k++]=R[j++];
free(L);
free(R);
}
void MERGE_SORT(int A[], int p, int r)
{
//During first iteration p = 1 & r = 8
if (p < r) {
int q = (p + r) / 2;
MERGE_SORT(A, p, q);
MERGE_SORT(A, q + 1, r);
MERGE(A, p, q, r);
}
}
/* Function to print an array */
void printArray(int Arr[], int size){
int i;
for (i = 0; i < size; i++)
printf("%d ", Arr[i]);
printf("\n");
}`
first of all you were not passing the right parameters to the function.
then the concept of using infinity to indicate is not good as one can want to sort bigger number than that in that case you would have to increase infinity an alternative approach is given above.
Mean while i also solved the problem with your code here it was again with the array index were not rightly used check it out now its working:`
#include<stdlib.h>
#include<stdio.h>
void MERGE(A, p, q, r);
void printArray(Arr, size);
void MERGE_SORT(A, p, r);
int main(void)
{
int A[] = { 12, 11, 13, 5, 6, 7, 2, 9 };
int arr_size = sizeof(A) / sizeof(A[0]);
printf("Given array is \n");
printArray(A, arr_size);
MERGE_SORT(A, 1, arr_size);
printf("\nSorted array is \n");
printArray(A, arr_size);
return 0;
}
void MERGE(int A[], int p, int q, int r)
{
int i = 0;
int j = 0;
int n1 = q - p + 1; //Computing length of sub-array 1
int n2 = r - q; //Computing length of sub-array 2
int *L = malloc((n1+1) * sizeof(*L+1)); //Creating Left array
int *R = malloc((n2+1) * sizeof(*R+1)); //Creating Right array
for (int i = 1; i < n1; i++) {
L[i] = A[p + i - 1];
}
for (int j = 1; j < n2; j++) {
R[j] = A[q + j];
}
L[n1] = 99; //Placing Sentinel at the end of array
R[n2] = 99;
i = 1;
j = 1;
/*Prior to the first iteration k = p, so the subarray is empty.
Both L[i] and R[j] are the smallest elements of their arrays and have not
been copied back to A*/
for (int k = p; k < r; k++) {
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
}
else if (A[k] == L[i])
j++;
}
free(L);
free(R);
}
void MERGE_SORT(int A[], int p, int r)
{
//During first iteration p = 1 & r = 8
if (p < r) {
int q = (p + r) / 2;
MERGE_SORT(A, p, q);
MERGE_SORT(A, q + 1, r);
MERGE(A, p, q, r);
}
}
/* Function to print an array */
void printArray(int Arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", Arr[i]);
printf("\n");
}