what is the correct time complexity of this function? - c

what my function does -> Given K sorted arrays arranged in form of a matrix. The task is to merge them. You need to complete mergeKArrays() function which takes 2 arguments, an arr[k][k] 2D Matrix containing k sorted arrays and an integer k denoting the number of sorted arrays. The function should return a pointer to the merged sorted arrays.
int *mergeKArrays(int arr[][N], int k)
{
// int *merged = (int*)malloc(sizeof(int) * k * k);
// do merge sort, as individual are already sorted
// just need to merge the arrays
int *a = arr[0];
int size_c = 2 * k;
int nb = k;
int na = k;
int *b;
int *c;
int ia, ib, ic;
for(int i = 1; i <= k - 1; ++i)
{
// merge(x, arr[i], k * i, k)
b = arr[i];
c = malloc(sizeof(int) * size_c);
if(c == NULL) exit(0);
ia = ib = ic = 0;
while(ia < na && ib < nb)
{
if(a[ia] < b[ib])
{
c[ic++] = a[ia++];
}
else
{
c[ic++] = b[ib++];
}
}
if(ia != na)
{
for(int i = ia; i < na; ++i)
{
c[ic++] = a[i];
}
}
if(ib != nb)
{
for(int i = ib; i < nb; ++i)
{
c[ic++] = b[i];
}
}
a = c;
na = size_c;
// printArray(a, na);
// printf("\n");
size_c = size_c + k;
}
return a;
}
my approach : the for loop runs x = (k-1)times....
each time array of size k is merged with i*k size array...(k+k) + (2k + k) + ....x times
= (k + k +...x times) +(k + 1k + 2k ....x times) = kx + kx(x-1)/2
which gives O(k^3). is this right ?
the actual size of arr given in main is k^2 (k by k matrix)
so n = k^2 => k = n^(0.5)
=> T(n) = O(n^(3/2)) ..??

Related

dealing with dups in end of the array

This is the task I have got:
I need to write a function (not recursive) which has two parameters.
An array of integers.
An integer representing the size of the array.
The function will move the duplicates to an end of the array.
And will give the size of the different digits.
Example:
5 , 2 , 4 , 5 , 6 , 7 , 2, n = 7
we will get back 5 , 2 , 4 , 6 , 7 , 5 , 2 and 5
We must keep the original sort as it is (which means like in example 5 must)
It does not matter how we sort the duplicates ones but just keep the sort for the original array as it is)
The function has to print the number of different digits (like in example 5)
The the input range of numbers in array [-n,n]
I can only use 1 additional array for help.
It has to be O(n)
I tried it so many times and feel like am missing something. Would appreciate any advice/suggestions.
int moveDup(int* arr, int n)
{
int* C = (int*)calloc(n * 2 + 1, sizeof(int));
assert(C);
/*int* count = C + n;*/
int *D = arr[0];
int value = 0, count = 0;
for (int i = 0; i < n; i++)
{
value = arr[i];
if (C[value + n] == 0)
{
*D = arr[i];
D++;
count++;
}
C[value + n] = C[value + n] + 1;
}
while (1 < C[value + n])
{
*D = i;
D++;
C[value + n]--;
}
free(C);
return count;
}
This algorithm will produce the required results in O(n) arithmetic complexity:
Input is an array A with n elements indexed from A0 to An−1 inclusive. For each Ai, −n ≤ Ai ≤ n.
Create an array C that can be indexed from C−n to C+n, inclusive. Initialize C to all zeros.
Define a pointer D. Initialize D to point to A0.
For 0 ≤ i < n:
If CAi=0, copy Ai to where D points and advance D one element.
Increment CAi.
Set r to the number of elements D has been advanced from A0.
For −n ≤ i ≤ +n:
While 1 < CAi:
Copy i to where D points and advance D one element.
Decrement CAi.
Release C.
Return r. A contains the required values.
A sample implementation is:
#include <stdio.h>
#include <stdlib.h>
#define NumberOf(a) (sizeof (a) / sizeof *(a))
int moveDuplicates(int Array[], int n)
{
int *memory = calloc(2*n+1, sizeof *Array);
if (!memory)
{
fprintf(stderr, "Error, unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
int *count = memory + n;
int *destination = Array;
for (int i = 0; i < n; ++i)
// Count each element. If it is unique, move it to the front.
if (!count[Array[i]]++)
*destination++ = Array[i];
// Record how many unique elements were found.
int result = destination - Array;
// Append duplicates to back.
for (int i = -n; i <= n; ++i)
while (0 < --count[i])
*destination++ = i;
free(memory);
return result;
}
int main(void)
{
int Array[] = { 5, 2, 4, 5, 6, 7, 2 };
printf("There are %d different numbers.\n",
moveDuplicates(Array, NumberOf(Array)));
for (int i = 0; i < NumberOf(Array); ++i)
printf(" %d", Array[i]);
printf("\n");
}
here is the right answer, figured it out by myself.
int moveDup(int* arr, int n)
{
int* seen_before = (int*)calloc(n * 2 + 1, sizeof(int));
assert(seen_before);
int val = 0, count = 0, flag = 1;
int j = 0;
for (int i = 0; i < n; i++)
{
val = arr[i];
if (seen_before[arr[i] + n] == 0)
{
seen_before[arr[i] + n]++;
count++;
continue;
}
else if (flag)
{
j = i + 1;
flag = 0;
}
while (j < n)
{
if (seen_before[arr[j] + n] == 0)
{
count++;
seen_before[arr[j] + n]++;
swap(&arr[i], &arr[j]);
j++;
if (j == n)
{
free(seen_before);
return count;
}
break;
}
/*break;*/
j++;
if (j == n)
{
free(seen_before);
return count;
}
}
}
}
second right answer
int* mem = (int*)calloc(2 * n + 1, sizeof * arr);
assert(mem);
int* count = mem + n;
int* dest = arr;
for (i = 0; i < n; ++i)
{
if (count[arr[i]]++ == 0)
{
*dest = arr[i];
*dest++;
}
}
res = dest - arr;
for (i = -n; i <= n; ++i)
{
while (0 < --count[i])
{
*dest++ = i;
}
}
free(mem);
return res;

As a result of processing arrays -nan(ind)

I am writing a program that creates arrays of a given length and manipulates them. You cannot use other libraries.
First, an array M1 of length N is formed, after which an array M2 of length N is formed/2.
In the M1 array, the division by Pi operation is applied to each element, followed by elevation to the third power.
Then, in the M2 array, each element is alternately added to the previous one, and the tangent modulus operation is applied to the result of addition.
After that, exponentiation is applied to all elements of the M1 and M2 array with the same indexes and the resulting array is sorted by dwarf sorting.
And at the end, the sum of the sines of the elements of the M2 array is calculated, which, when divided by the minimum non-zero element of the M2 array, give an even number.
The problem is that the result X gives is -nan(ind). I can't figure out exactly where the error is.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
const int A = 441;
const double PI = 3.1415926535897931159979635;
inline void dwarf_sort(double* array, int size) {
size_t i = 1;
while (i < size) {
if (i == 0) {
i = 1;
}
if (array[i - 1] <= array[i]) {
++i;
}
else
{
long tmp = array[i];
array[i] = array[i - 1];
array[i - 1] = tmp;
--i;
}
}
}
inline double reduce(double* array, int size) {
size_t i;
double min = RAND_MAX, sum = 0;
for (i = 0; i < size; ++i) {
if (array[i] < min && array[i] != 0) {
min = array[i];
}
}
for (i = 0; i < size; ++i) {
if ((int)(array[i] / min) % 2 == 0) {
sum += sin(array[i]);
}
}
return sum;
}
int main(int argc, char* argv[])
{
int i, N, j;
double* M1 = NULL, * M2 = NULL, * M2_copy = NULL;
double X;
unsigned int seed = 0;
N = atoi(argv[1]); /* N равен первому параметру командной строки */
M1 = malloc(N * sizeof(double));
M2 = malloc(N / 2 * sizeof(double));
M2_copy = malloc(N / 2 * sizeof(double));
for (i = 0; i < 100; i++)
{
seed = i;
srand(i);
/*generate*/
for (j = 0; j < N; ++j) {
M1[j] = (rand_r(&seed) % A) + 1;
}
for (j = 0; j < N / 2; ++j) {
M2[j] = (rand_r(&seed) % (10 * A)) + 1;
}
/*map*/
for (j = 0; j < N; ++j)
{
M1[j] = pow(M1[j] / PI, 3);
}
for (j = 0; j < N / 2; ++j) {
M2_copy[j] = M2[j];
}
M2[0] = fabs(tan(M2_copy[0]));
for (j = 0; j < N / 2; ++j) {
M2[j] = fabs(tan(M2[j] + M2_copy[j]));
}
/*merge*/
for (j = 0; j < N / 2; ++j) {
M2[j] = pow(M1[j], M2[j]);
}
/*sort*/
dwarf_sort(M2, N / 2);
/*sort*/
X = reduce(M2, N / 2);
}
printf("\nN=%d.\n", N);
printf("X=%f\n", X);
return 0;
}
Knowledgeable people, does anyone see where my mistake is? I think I'm putting the wrong data types to the variables, but I still can't solve the problem.
Replace the /* merge */ part with this:
/*merge*/
for (j = 0; j < N / 2; ++j) {
printf("%f %f ", M1[j], M2[j]);
M2[j] = pow(M1[j], M2[j]);
printf("%f\n", M2[j]);
}
This will print the values and the results of the pow operation. You'll see that some of these values are huge resulting in an capacity overflow of double.
Something like pow(593419.97, 31.80) will not end well.

problem calculating the inverse of a matrix

I'm trying to calculate the inverse of a square matrix of any rank N x N. I'm using a struct to store the values of the matrix which I can to effectively and I am already able to calculate the determinant. But there must be some issue with the inverse function. This is the code
struct m{
size_t row;
size_t col;
double *data;
};
void inverse(size_t n, struct m *A) /*Calculate the inverse of A */
{
size_t i,j,i_count,j_count, count=0;
double det = determinant(n, A);
size_t id = 0;
double *d;
struct m C; /*The Adjoint matrix */
C.data = malloc(sizeof(double) * n * n);
C.row = n;
C.col = n;
struct m *minor; /*matrices obtained by removing the i row and j column*/
if (!(minor = malloc(n*n*(n+1)*sizeof *minor))) {
perror ("malloc-minor");
exit(-1);
}
if (det == 0){
printf("The matrix is singular\n");
exit(1);
}
for(id=0; id < n*n; id++){
d = minor[id].data = malloc(sizeof(double) * (n-1) * (n-1));
for(count=0; count < n; count++)
{
//Creating array of Minors
i_count = 0;
for(i = 0; i < n; i++)
{
j_count=0;
for(j = 0; j < n; j++)
{
if(j == count)
continue; // don't copy the minor column element
*d = A->data[i * A->col + j];
d++;
j_count++;
}
i_count++;
}
}
}
for(id=0; id < n*n; id++){
for(i=0; i < n; i++){
for(j=0; j < n; j++)
C.data[i * C.col + j] = determinant(n-1,&minor[id]);//Recursive call
}
}
transpose(&C);
scalar_product(1/det, &C);
*A = C;
}
The determinant is calculated recursively with this algorithm:
double determinant(size_t n, struct m *A)
{
size_t i,j,i_count,j_count, count=0;
double det = 0;
if(n < 1)
{
printf("Error\n");
exit(1);
}
if(n==1) return A->data[0];
else if(n==2) return (A->data[0]* A->data[1 * A->col + 1] - A->data[0 + 1] * A->data[1*A->col + 0]);
else{
struct m C;
C.row = A->row-1;
C.col = A->col-1;
C.data = malloc(sizeof(double) * (A->row-1) * (A->col-1));
for(count=0; count < n; count++)
{
//Creating array of Minors
i_count = 0;
for(i = 1; i < n; i++)
{
j_count=0;
for(j = 0; j < n; j++)
{
if(j == count)
continue; // don't copy the minor column element
C.data[i_count * C.col + j_count] = A->data[i * A->col + j];
j_count++;
}
i_count++;
}
det += pow(-1, count) * A->data[count] * determinant(n-1,&C);//Recursive call
}
free(C.data);
return det;
}
}
You can find the complete code here: https://ideone.com/gQRwVu.
Use some other variable in the loop after :
det + =pow(-1,count) * A->data[count] *determinant (n-1,&C)
Your calculation of the inverse doesn't quite correspond to the algorithm described e. g. for Inverse of a Matrix
using Minors, Cofactors and Adjugate, even taken into account that you for now omitted the adjugate and division step. Compare your outermost for loop in inverse() to this working implementation:
double Rdata[(n-1)*(n-1)]; // remaining data values
struct m R = { n-1, n-1, Rdata }; // matrix structure for them
for (count = 0; count < n*n; count++) // Create n*n Matrix of Minors
{
int row = count/n, col = count%n;
for (i_count = i = 0; i < n; i++)
if (i != row) // don't copy the current row
{
for (j_count = j = 0; j < n; j++)
if (j != col) // don't copy the current column
Rdata[i_count*R.col+j_count++] = A->data[i*A->col+j];
i_count++;
}
// transpose by swapping row and column
C.data[col*C.col+row] = pow(-1, row&1 ^ col&1) * determinant(n-1, &R) / det;
}
It yields for the given input data the correct inverse matrix
1 2 -4.5
0 -1 1.5
0 0 0.5
(already transposed and divided by the determinant of the original matrix).
Minor notes:
The *A = C; at the end of inverse() loses the original data pointer of *A.
The formatting function f() is wrong for negative values, since the fraction is also negative in this case. You could write if (fabs(f)<.00001).

In merge_sort algorithm, It works when parameter is double type list, but not when it is int type list

I want to sort the int type list. but when parameter in merge function is double list, it works! but not when it is int list...
Here is sorting function. parameter is int pointer.
if Changing an int list to a double list works fine.
ex) int *a -> double *a
ex) int *l, *r1 -> double *l, *r1
ex) l = (int *)calloc(n1+1,sizeof(int)), r1 = (int *)calloc(n2+1,sizeof(int))
-> l = (double *)calloc(n1+1,sizeof(double)) r1 = (double *)calloc(n2+1,sizeof(double))
void merge(int *a, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int *l, *r1;
int i, j, k;
l = (int *)calloc(n1 + 1, sizeof(int));
r1 = (int *)calloc(n2 + 1, sizeof(int));
for (i = 0; i < n1;i++)
l[i] = a[p + i];
for (j = 0; j < n2; j++)
r1[j] = a[q + 1 + j];
l[n1] = 10000;
r1[n2] = 10000;
i = 0;
j = 0;
for (k = p; k <= r; k++) {
if (l[i] <= r1[j]) {
a[k] = l[i];
++i;
} else {
a[k] = r1[j];
++j;
}
}
return;
}
here is recursive function. Until the length of the list is 1
ex) int *a -> double *a
void merge_sort(int *a, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
merge_sort(a, p, q);
merge_sort(a, q + 1, r);
merge(a, p, q, r);
}
}
Create a list of length 10 and put it in the mergesort function. Then print the list.
int main(int argc, char *argv[]) {
int i, *a[10];
for (i = 0; i < 10; i++) {
a[i] = rand() % 10 + 1;
}
merge_sort(a, 0, 10);
for (i = 0; i < 10; i++) {
printf("%d ", a[i]);
}
return 0;
}
result is
0 0 0 2 5 10 9 9 3 5
There are multiple problems in your code:
if you wish to change the type of the array element, you must change it everywhere, including in the main function and you must also change the printf format. Increasing the warning level (gcc -Wall -Wextra -Werror) would prevent silly mistakes.
the definition of a in main is incorrect, it should be int a[10];, not an array of pointers to int.
you pass the total number of elements to mergesort() in main: merge_sort(a, 0, 10); which means r in merge sort should be excluded. The recursive call merge_sort(a, q + 1, r); in mergesort is then incorrect as q should be excluded in merge_sort(a, p, q); but included in the second half. Use merge_sort(a, q, r); instead.
you compute the middle of the segment with int q = (p + r) / 2;. You may have undefined behavior for large arrays as q + r may overflow the range of type int. This is a classic bug that can go unnoticed for decades until someone uses the code for a large array. Use int q = p + (r - p) / 2; to avoid it.
the algorithm in merge is incorrect: you assume that all values in the arrays are < 10000, which may be an invalid assumption. The code should handle all possible values. You should test the index variables to detect the end of the subarrays and handle the remaining values of the other array specifically.
you do not free the arrays allocated in merge, causing memory leaks.
to make it easier to change the element type, you could use a typedef.
Here is a improved version:
#include <stdio.h>
#ifdef USE_DOUBLE
typedef double sorttype;
#else
typedef int sorttype;
#endif
void merge(sorttype *a, int p, int q, int r) {
// merge subarrays a[p...q] and a[q...r]
// upper bounds q and r are excluded
int n1 = q - p;
int n2 = r - q;
sorttype *a1, *a2;
int i, j, k;
a1 = malloc(n1 * sizeof(*a1));
a2 = malloc(n2 * sizeof(*a2));
for (i = 0; i < n1; i++)
a1[i] = a[p + i];
for (j = 0; j < n2; j++)
a2[j] = a[q + j];
i = 0;
j = 0;
for (k = p; k < r; k++) {
if (i < n1 && (j >= n2 || a1[i] <= a2[j])) {
a[k] = a1[i];
++i;
} else {
a[k] = a2[j];
++j;
}
}
free(a1);
free(a2);
}
void merge_sort(sorttype *s, int p, int r) {
if (r - p > 1) {
int q = p + (r - p) / 2;
merge_sort(s, p, q);
merge_sort(s, q, r);
merge(s, p, q, r);
}
}
int main(int argc, char *argv[]) {
sorttype a[10];
int i;
for (i = 0; i < 10; i++) {
a[i] = 1 + rand() % 10;
}
merge_sort(a, 0, 10);
for (i = 0; i < 10; i++) {
#ifdef USE_DOUBLE
printf("%g ", a[i]);
#else
printf("%d ", a[i]);
#endif
}
printf("\n");
return 0;
}
Output for int:
1 3 4 4 5 8 9 9 10 10
Output for double:
1 3 4 4 5 8 9 9 10 10
Notice how the random numbers are identical although the program was recompiled and re-run... You should use srand(clock()) to try and get a different pseudo-random sequence.
Note also that allocating a2 to make a copy of the right subarray is not required because the merge operation never overwrites elements from the right half that have not already been copied.
Furthermore, you should test for allocation failure and report it.
Here is an improved version of merge:
void merge(sorttype *a, int p, int q, int r) {
// merge subarrays a[p...q] and a[q...r]
// upper bounds q and r are excluded
int n1 = q - p;
int n2 = r - q;
sorttype *a1;
int i, j, k;
a1 = malloc(n1 * sizeof(*a1));
if (a1 == NULL) {
fprintf(stderr, "memory allocation failure\n");
exit(1);
}
for (i = 0; i < n1; i++)
a1[i] = a[p + i];
i = 0;
j = 0;
for (k = p; i < n1 && k < r; k++) {
if (j >= n2 || a1[i] <= a[q + j]) {
a[k] = a1[i];
++i;
} else {
a[k] = a[q + j];
++j;
}
}
free(a1);
}

how can I transpose a 2D matrix in place in C?

I'm trying to transpose a 2D matrix (10x10) in place:
for (a = 0; a < 10; a++) {
for (b = 0; b < 10; b++) {
tmp = matrix[a][b];
matrix[b][a] = matrix[a][b];
matrix[a][b] = tmp;
}
}
If I can increase the starting value 'b' of the inner for statement by 1, it works fine.
However, when one loop is turned, the value of the variable is set to 0. It is very natural.
Is there a way to increase the starting value 'b' of the inner for loop after running around a loop?
I really want to solve this problem.
Can you use global variables or any other way to solve this problem?
Your swapping code is incorrect: you should overwrite the saved value first.
Furthermore, you must stop the inner loop when b == a, otherwise the values would be swapped twice, and the transposition would fail.
Here is a corrected version:
/* swap values on either side of the first diagonal */
for (a = 1; a < 10; a++) {
/* stop the inner loop when b == a */
for (b = 0; b < a; b++) {
int tmp = matrix[a][b];
matrix[a][b] = matrix[b][a];
matrix[b][a] = tmp;
}
}
This simple algorithm is not cache optimal for large matrices, especially for power of 2 sizes. More elaborate algorithms have been developed for in place matrix transpostion.
For example, here is a benchmark for 1024x1024 matrices comparing the naive algorithm with an advanced recursive approach:
#include <stdio.h>
#include <time.h>
#define SIZE 1024
static int mat[SIZE][SIZE];
void initialize_matrix(int matrix[SIZE][SIZE]) {
int a, b, x = 0;
for (a = 0; a < SIZE; a++) {
for (b = 0; b < SIZE; b++) {
mat[a][b] = x++;
}
}
}
int check_transpose_matrix(int matrix[SIZE][SIZE]) {
int a, b, x = 0;
for (a = 0; a < SIZE; a++) {
for (b = 0; b < SIZE; b++) {
if (mat[b][a] != x++)
return 1;
}
}
return 0;
}
void naive_transpose(int matrix[SIZE][SIZE]) {
/* swap values on either side of the first diagonal */
for (int a = 1; a < SIZE; a++) {
/* stop the inner loop when b == a */
for (int b = 0; b < a; b++) {
int tmp = matrix[a][b];
matrix[a][b] = matrix[b][a];
matrix[b][a] = tmp;
}
}
}
#define THRESHOLD 4
void transpose_tile(int row, int col, int size, int matrix[SIZE][SIZE]) {
if (size > THRESHOLD) {
transpose_tile(row, col, size / 2, matrix);
transpose_tile(row, col + size / 2, size / 2, matrix);
transpose_tile(row + size / 2, col, size / 2, matrix);
transpose_tile(row + size / 2, col + size / 2, size / 2, matrix);
} else {
for (int a = 0; a < size; a++) {
for (int b = 0; b < size; b++) {
int tmp = matrix[row + a][col + b];
matrix[row + a][col + b] = matrix[col + b][row + a];
matrix[col + b][row + a] = tmp;
}
}
}
}
void transpose_tile_diag(int pos, int size, int matrix[SIZE][SIZE]) {
if (size > THRESHOLD) {
transpose_tile_diag(pos, size / 2, matrix);
transpose_tile(pos, pos + size / 2, size / 2, matrix);
transpose_tile_diag(pos + size / 2, size / 2, matrix);
} else {
/* swap values on either side of the first diagonal */
for (int a = 1; a < size; a++) {
/* stop the inner loop when b == a */
for (int b = 0; b < a; b++) {
int tmp = matrix[pos + a][pos + b];
matrix[pos + a][pos + b] = matrix[pos + b][pos + a];
matrix[pos + b][pos + a] = tmp;
}
}
}
}
void advanced_transpose(int matrix[SIZE][SIZE]) {
transpose_tile_diag(0, SIZE, matrix);
}
int main(int argc, char *argv[]) {
clock_t t_min;
initialize_matrix(mat);
naive_transpose(mat);
if (check_transpose_matrix(mat)) {
printf("naive_transpose failed!\n");
return 1;
}
/* benchmark naive algorithm */
t_min = 0;
for (int i = 0; i < 100; i++) {
clock_t t = clock();
naive_transpose(mat);
t = clock() - t;
if (i == 0 || t_min > t)
t_min = t;
}
printf("naive: %.3fms\n", t_min * 1000.0 / CLOCKS_PER_SEC);
initialize_matrix(mat);
advanced_transpose(mat);
if (check_transpose_matrix(mat)) {
printf("advanced_transpose failed!\n");
return 1;
}
/* benchmark advanced algorithm */
t_min = 0;
for (int i = 0; i < 100; i++) {
clock_t t = clock();
advanced_transpose(mat);
t = clock() - t;
if (i == 0 || t_min > t)
t_min = t;
}
printf("advanced: %.3fms\n", t_min * 1000.0 / CLOCKS_PER_SEC);
return 0;
}
Output on my 5 year old macbook:
naive: 7.299ms
advanced: 1.157ms

Resources