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;
}
Related
I have a code that requires me to do this thing :
Input size of array and testcases.
A character of Operatiion such as (I,A,D,Q) and elements of array.
I : Adding an element into the array.
A : Will change data in the database to a new data that is not exist in
the database.
D : Delete data which has value X from database.
Q : Show all data that less than equal X from database.
Input :
<size of Array> <operations/testcase>
<I/A/D/Q> <elements of array with X value>
The example of input :
Input :
6 4
3 2 3 1 5 6
I 7
D 6
A 3 5
Q 7
Output :
6 (because only 1 Q operation)
I already created the program, but I think this is not efficient enough because it take a longer time to execute. My question is what should I do to make my program more efficient?
#include "stdio.h"
#define MAXSIZE 99999
void swap(int *a,int *b){
int temp = *a;
*a = *b;
*b = temp;
}
void printArr(int arr[]){
for(int i = 0; arr[i] != NULL; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
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; // 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++;
}
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);
}
}
int binarySearch(int arr[], int left, int right,int num){
if(right >= left){
int mid = (left + right) / 2;
if(num == arr[mid]) return mid;
if(arr[mid] > num) return binarySearch(arr, left, mid-1, num);
else return binarySearch(arr,mid+1,right, num);
}
return -1;
}
int main(int argc, char const *argv[])
{
int operations, sizeArr, numX, numY, arr[MAXSIZE];
char type;
scanf("%d %d",&sizeArr,&operations); getchar();
int index = 0, counter = 0;
for(index = 0; index < sizeArr; index++){
scanf("%d",&arr[index]); getchar();
}
mergeSort(arr, 0, sizeArr - 1);
int left = 0, deleted = 0;
for(int j = 0; j < operations; j++){
scanf("%c",&type); getchar();
if(type == 'I'){
scanf("%d",&numX); getchar();
arr[index++] = numX;
sizeArr++;
}
else if(type == 'A'){
scanf("%d %d",&numX, &numY); getchar();
mergeSort(arr, 0, sizeArr - 1);
for(int i = deleted; arr[i] != NULL ; i++){
if(arr[i] == numX){
int old = arr[i];
arr[i] = numY;
if(arr[i + 1] != old) break;
}
}
}
else if(type == 'D'){
scanf("%d",&numX); getchar();
for(int i = 0; arr[i] != NULL ; i++){
if(arr[i] == numX){
int old = arr[i];
arr[i] = -1;
deleted++;
if(arr[i + 1] != old) break;
// sizeArr--;
}
}
mergeSort(arr, 0, sizeArr - 1);
}
else if(type == 'Q'){
scanf("%d",&numX); getchar();
mergeSort(arr, 0, sizeArr - 1);
// printArr(arr);
for(int i = deleted; i < sizeArr ; i++){
if(arr[i] <= numX && arr[i] > -1){
counter++;
// printf("%d\n",arr[i]);
}
else break;
}
printf("%d\n",counter);
counter = 0;
}
// printf("Size Arr : %d\n", sizeArr);
// printf("Deleted : %d\n",deleted);
// printArr(arr);
}
return 0;
}
Could you please tell me my mistake to my program more efficient on time limit?
They didn't mention the time limit duration. It only gives 5/10 testcase that correct. So I need to find another efficient way to make my code goes faster.
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]; ... }
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
}
My C merge code works when I initialize the array globally at the top of the program until the stack overflows. I'm trying to initialize the array with malloc, but when I do, the code will only read in two integers and stop running.
This program pulls random numbers from a file called alg.txt and then sorts them. Again, the code works (up until 500k integers) when defining z at the top of the program to the number of integers to be sorted, and declaring the array globally to be equal to arr[z]. How do I figure out what is going on?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int count = 0;
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];
count++;
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
count++;
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
count++;
}
else
{
arr[k] = R[j];
j++;
count++;
}
k++;
count++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
count++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
count++;
}
}
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 i;
FILE *myFile;
myFile = fopen("alg.txt", "r");
int z;
printf("Enter the size of the array: ");
scanf("%d", &z);
int *arr = (int *)malloc(z*sizeof(int));
int n = sizeof(arr)/sizeof(arr[0]);
for(i=0; i < z; i++)
{
fscanf(myFile, "%d,", &arr[i]);
}
mergeSort(arr, 0, n - 1);
printf("\nSorted array is \n");
printArray(arr, n);
printf("count is %d\n", count);
return 0;
}
You are declaring the L and R array's locally (inside the merge function). They consume stack on every function call. You should initialize them globally so that they can be stored on the heap. Also, you should declare just one array (like temp_arr in the below code) as there's no need for two separate arrays like L and R.
See Local vs Global variable storage
You can improve your merge function to this:
int temp_arr[500000]; // Global declaration
void merge(int arr[], int l, int m, int r)
{
int i=l, j=m+1, k=l;
while(i<=m && j<=r)
{
if(arr[i]<arr[j])
temp_arr[++k] = arr[++i];
else temp_arr[++k] = arr[++j];
}
while(i<=m)
temp_arr[++k] = arr[++i];
while(j<=r)
temp_arr[++k] = arr[++j];
i = l;
while(i<=r)
arr[i] = temp_arr[++i]; // Storing stored array in arr
}
I am trying to implement the merge sort algorithm in C. I understand how the algorithm is supposed to work however I am encountering some difficulties with the implementation.
I understand that there are hundreds of examples and source code for it's implementation but I was hoping someone could help me understand why mine is not working correctly.
My code is below and after the code I explain what I have tried so far.
#include <stdio.h>
void merge(int a[], int L[], int R[],int nL, int nR) //nL and nR are the lengths of L[] and R[]
{
int i = 0 , j = 0, k = 0;
while(i<nL && j <nR)
{
if(L[i] <= R[j]){
a[k] = L[i];
i++;
}
else{
a[k] = R[j];
j++;
}
k++;
}
while(i < nL){
a[k] = L[i];
i++;
k++;
}
while(j < nR) {
a[k] = R[j];
j++;
k++;
}
}
void mergesort(int a[],int n) //n is the length of a[]
{
if(n < 2) return; //BASE CASE
int mid = n / 2;
int left[mid];
int right[n-mid];
for(int i = 0; i < mid; i++)
{
left[i] = a[i];
}
for(int i = mid; i < n-1; i++)
{
right[i-mid] = a[i];
}
int nL = sizeof(left) / sizeof(left[0]);
int nR = sizeof(right) / sizeof(right[0]);
mergesort(left, nL);
mergesort(right, nR);
merge(a,left,right,nL,nR);
}
int main(void)
{
printf("Initial:\n");
printf("3 4 1 6\n");
int numbers[4] = {3,4,1,6};
int n = sizeof(numbers) / sizeof(int);
mergesort(numbers,n);
printf("Sorted:\n");
for(int i =0 ; i < 4; i++)
{
printf("%d ", numbers[i]);
}
return 0;
}
As it is and with the unsorted array [3,4,1,6] the output is 0 0 1 3.
Clearly the 1 and 3 are in the right order relative to each other but the two zeros at the beginning are clearly wrong. At first it seemed to me that I was inserting 4 and 6 to the right and out of bounds of the array.
I used some print statements to try and debug but I haven't been able to figure out what was going on. I even tried to follow my code with gdb but I still could not sort it.
Does any one have any ideas of what might be happening?
A more nearly idiomatic way of writing the merge() code would be:
void merge(int a[], int L[], int R[],int nL, int nR)
{
int i = 0, j = 0, k = 0;
while (i < nL && j < nR)
{
if (L[i] <= R[j])
a[k++] = L[i++];
else
a[k++] = R[j++];
}
while (i < nL)
a[k++] = L[i++];
while (j < nR)
a[k++] = R[j++];
}
That's about half the number of lines of your code, and within broad limits, the less code there is to read, the better. There are those who insist on having braces after each loop or conditional. I don't think that's necessary (or particularly helpful), but if that's the style you like, you can use it.
Your mergesort() code is less flabby, but could be changed to:
void mergesort(int a[],int n) //n is the length of a[]
{
if (n < 2)
return; //BASE CASE
int mid = n / 2;
int left[mid];
int right[n-mid];
for (int i = 0; i < mid; i++)
left[i] = a[i];
for (int i = mid; i < n; i++)
right[i-mid] = a[i];
mergesort(left, mid);
mergesort(right, n - mid);
merge(a, left, right, mid, n - mid);
}
This includes the fix for your main problem — the loop loading the right array was leaving the last element uncopied.
With a debugging function such as:
void dump_array(const char *tag, int n, int *a)
{
printf("%s:%d:", tag, n);
for (int i = 0; i < n; i++)
printf(" %3d", a[i]);
putchar('\n');
}
You can do a lot of effective debugging with:
void mergesort(int a[],int n)
{
if (n < 2)
return;
int mid = n / 2;
int left[mid];
int right[n-mid];
dump_array("-->>mergesort()", n, a);
for (int i = 0; i < mid; i++)
left[i] = a[i];
dump_array("left", mid, left);
for (int i = mid; i < n; i++)
right[i-mid] = a[i];
dump_array("right", n - mid, right);
mergesort(left, mid);
dump_array("merged-L", mid, left);
mergesort(right, n - mid);
dump_array("merged-R", n - mid, right);
merge(a, left, right, mid, n - mid);
dump_array("<<--mergesort()", n, a);
}
In your code, the output with the tag right would show 0 or semi-random data for the last element, rather than what you're expecting. This would be a hint as to where the trouble is. Keep the dump_array() function around; it is a useful creature to have. It's a simple-minded version; you can invent more complex versions which outputs a newline at intermediate positions for long arrays, for example.
The issue is in the following code:
for(int i = mid; i < n-1; i++)
{
right[i-mid] = a[i];
}
It should be:
for(int i = mid; i < n; i++) // right should range from mid to n - 1 *inclusive*
{
right[i-mid] = a[i];
}
This is simple implementation of merge sort without any complications. Just pass the array pointer and total number of entires in the array.
void merge(int *a, int top)// Array pointer and max entries
{
int l1, k, l2, u1, u2, size = 1, i, j;
int *sa;
sa = (int *)calloc(top, sizeof(int));
while (size < top)
{
l1 = 0;
k = 0;
while (l1 + size < top)
{
l2 = l1 + size;
u1 = l2 - 1;
u2 = ((l2 + size - 1) < top ? l2 + size - 1 : top - 1);
for (i = l1, j = l2; i <= u1 && j <= u2; )// Merging
{
sa[k++] = a[i] <= a[j] ? a[i++] : a[j++];
}
for ( ; i <= u1; )
sa[k++] = a[i++];
for ( ; j <= u2; )
sa[k++] = a[j++];
l1 = u2 + 1;
}
for (i = l1; i < top; i++) // For the left outs of the process
sa[k++] = a[i];
for (i = 0; i < top; i++)
a[i] = sa[i];
size *= 2;
}
}