The task is to insert an element into each matrix row in 2 ways: iterative and recoursive. I've completed iterative one, but don't understand how to change it to recoursive. Appreciate any help. Here is my function, n
- number row elements, key
- the value to implement in rows:
void insertSorted(int arr[], int n, int key)
{
int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];
arr[i + 1] = key;
}
And here is the code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define MAX 10
void insertSorted(int arr[], int n, int key)
{
int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];
arr[i + 1] = key;
}
int main()
{
int arr[MAX][MAX];
int row, col;
int i, key;
printf("Enter the matrix size:\nRows: ");
scanf("%d", &row);
printf("Cols: ");
scanf("%d", &col);
printf("\nEnter %dx%d matrix with sorted rows:\n", row, col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
scanf("%d", &arr[i][j]);
printf("\nBefore Insertion:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
printf("%d ", arr[i][j]);
puts(" ");
}
printf("\nEnter the number to insert in rows: ");
scanf("%d", &key);
for (int i = 0; i < row; i++)
insertSorted(arr[i], col, key);
col++;
printf("\nAfter Insertion:\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
printf("%d ", arr[i][j]);
puts("");
}
return 0;
}
void RecursiveInsertSorted(int arr[], int n, int key)
{
if(n==0)
arr[n]=key;
return;
if(arr[n-1]>key){
arr[n]=arr[n-1];
RecursiveInsertSorted(arr,n-1,key);
}
else{
arr[n]=key;
return;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.