I was asked this question in an interview. I am given a 2D array of random numbers(numbers can be repeated) and I need to sort them both row and column wise i.e. all the rows and columns should be sorted. Can anyone please explain how to do it efficiently(min time and space complexity). If you can give a code in C or C++ then that would be really helpful
My idea is that a 2D array can (in some cases) be considered as a 1D array because of the memory storage of it. If not, you can either copy it into a 1D array of write a custom sort function that use a function that translate the indexes from 1D to 2D.
Here an example using the function qsort:
#include <stdio.h>
#include <stdlib.h>
int matrix[4][4];
void print_matrix() {
int i, j;
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int compar(const void *a, const void *b) {
int ia = *((int*)a);
int ib = *((int*)b);
return ia - ib;
}
int main() {
int i, j;
// Init of a 2D array with random numbers:
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
matrix[i][j] = random() % 10;
}
}
// Before:
printf("Before:\n");
print_matrix();
// This array can be considered as a big 1D array.
qsort(matrix, 16, sizeof(int), compar);
// After:
printf("After:\n");
print_matrix();
return 0;
}
Output:
Before:
3 6 7 5
3 5 6 2
9 1 2 7
0 9 3 6
After:
0 1 2 2
3 3 3 5
5 6 6 6
7 7 9 9
Edit: OP asked me to avoid using qsort... So here a quicksort able to sort a 2D array:
#include <stdio.h>
#include <stdlib.h>
void print_matrix(int **matrix, int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
void swap(int *a, int *b) {
int buf = *a;
*a = *b;
*b = buf;
}
int partition(int **a, int l, int r, int c) {
int i;
// Left pivot
int pivot_val = a[l/c][l%c];
// Move pivot to end
swap(&a[l/c][l%c], &a[r/c][r%c]);
// If <= to the pivot value, swap
int j = l;
for (i = l; i < r; i++) {
if (a[i/c][i%c] <= pivot_val) {
swap(&a[i/c][i%c], &a[j/c][j%c]);
j++;
}
}
// Move pivot to its place.
swap(&a[j/c][j%c], &a[r/c][r%c]);
return j;
}
void quicksort_r(int **a, int l, int r, int c) {
if (l < r) {
int pivot = partition(a, l, r, c);
quicksort_r(a, l, pivot-1, c);
quicksort_r(a, pivot+1, r, c);
}
}
void quicksort(int **a, int rows, int cols) {
quicksort_r(a, 0, rows * cols - 1, cols);
}
int main() {
int i, j;
int rows = 5;
int cols = 4;
int **matrix = malloc(sizeof(int*) * rows);
// Init of a 2D array with random numbers:
for (i = 0; i < rows; i++) {
matrix[i] = malloc(sizeof(int) * cols);
for (j = 0; j < cols; j++) {
matrix[i][j] = random() % 10;
}
}
// Before:
printf("Before:\n");
print_matrix(matrix, rows, cols);
quicksort(matrix, rows, cols);
// After:
printf("After:\n");
print_matrix(matrix, rows, cols);
return 0;
}
Which gives:
Before:
3 6 7 5
3 5 6 2
9 1 2 7
0 9 3 6
0 6 2 6
After:
0 0 1 2
2 2 3 3
3 5 5 6
6 6 6 6
7 7 9 9
Edit2: I realized afterward that there is another obvious solution for square matrices:
Let's take the first example:
0 1 2 2
3 3 3 5
5 6 6 6
7 7 9 9
There is also:
0 3 5 7
1 3 6 7
2 3 6 9
2 5 6 9
But for the second example too:
0 0 1 2
2 2 3 3
3 5 5 6
6 6 6 6
7 7 9 9
And:
0 2 3 6
0 2 5 6
1 3 5 6
2 3 6 6
7 7 9 9
Which means that maybe we could do a specialized algorithm able to give all the solutions or an algorithm that tries to minimize the number of moves, I don't know. It's a quite interesting problem in fact.
Try using and adapting this...
void sort(int MyArray[8][8])
{
for(int ir=0;ir<8;ir++)
{
for(int ic=0;ic<8;ic++)
{
for(int jr=0;jr<8;jr++)
{
for(int jc=0;jc<8;jc++)
{
if(MyArray[ir][jr]>MyArray[ic][jc])
{
int temp=MyArray[ir][jr];
MyArray[ir][jr]=MyArray[ic][jc];
MyArray[ic][jc]=temp;
}
}
}
}
}
}
This is a simple bubble sort. It effectively runs on O(n^4) You can get more effective by writing an algorithm such as quicksort. I have never seen or even thought of attempting a quicksort on a 2D array. it is not going to be easy. What you can try is adding everything into a single array, quicksort it and copy everything back into a 2D array. but the array has to be very large before it will be more effective... If someone does give a quicksort or merge sort algorithm here for a 2D array. He deserves a Medal! that is hardcore
Related
I wanted to know if I could get some help creating a square matrix. I know how to create the matrix, but I need to populate the matrix. I am having trouble following the logic to create the following matrix:
0 1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 9 10
Here is what I have in my code thus far:
EDIT*
I have changed the else statement from arr[i][j] += 1 to arr[i][j-1] + 1
void computeMatrix(int rows, int cols, int sqMatrix[][cols]){
int i,j;
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
if(i == 0 && j == 0){
arr[i][j] = 0;
}
else{
arr[i][j] = arr[i][j-1] + 1; //previously arr[i][j] += 1
}
}
}
}
The issue I am having is that this code makes the following matrix:
0 1 2 3 4 5
6 7 8 9 10 11
12 13 14 15 16 17
18 19 20 21 22 23
24 25 26 27 28 29
30 31 32 33 34 35
I am not sure what type of logic to implement to get the matrix correct. I have a general idea, but I am not sure how to implement it to the code. I know that as we go down the rows, we increase by 1, and as we go through the columns, we increase by 1 as well.
Any help I could get will be greatly appreciated!
The elements of the first matrix can be set with:
a[i][j] = i + j;
There's no need for an if statement inside the loop. The whole thing looks like:
void computeMatrix(int rows, int cols, int sqMatrix[][cols])
{
int i,j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
arr[i][j] = i + j;
}
}
}
void computeMatrix(const size_t rows, const size_t cols, int *arr)
{
for(size_t r = 0; r < rows; r++)
{
for(size_t c = 0; c < cols; c++)
{
arr[r * cols + c] = c + r;
}
}
}
void printmatriz(const int rows, const int cols, int *arr)
{
for(size_t r = 0; r < rows; r++)
{
for(size_t c = 0; c < cols; c++)
{
printf("%2d ", arr[r * cols + c]);
}
printf("\n");
}
}
#define X 6
#define Y 6
int main(void)
{
int arr[X][Y];
computeMatrix(X,Y,&arr[0][0]);
printmatriz(X,Y, &arr[0][0]);
}
How do I create a square matrix in the C programming language?
You think of it as an abstract data type, using C dynamic memory allocation.
This answer gives details and code and uses flexible array members.
Read the Modern C book
I wrote a serial program to generate 2 random matrices, multiply them and display the result. I wrote functions for each of the tasks, i.e. generating random matrix, multiplying the matrices and displaying the results. I cannot figure out why both the generated matrices are the same.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int **matrix_generator(int row,int col);
int **multiply_matrices(int **matrix_A,int **matrix_B,int rowsA, int colsA,int rowsB,int colsB);
void display_result(int **matrix,int cols,int rows);
void display_matrix(int **matrixA,int cols,int rows);
void main()
{
int **matrix_A,**matrix_B,**matrix_result,i,j,k,tid,rowsA,colsA,rowsB,colsB;
printf("Enter the dimensions of Matrix A:\n");
scanf("%d%d",&rowsA,&colsA);
printf("Enter the dimensions of Matrix B:\n");
scanf("%d%d",&rowsB,&colsB);
if(colsA==rowsB)
{
matrix_A = matrix_generator(rowsA,colsA);
matrix_B = matrix_generator(rowsB,colsB);
matrix_result = multiply_matrices(matrix_A,matrix_B,rowsA,colsA,rowsB,colsB);
printf("Matrix A:\n");
display_matrix(matrix_A,rowsA,colsA);
printf("\n\n");
printf("Matrix B:\n");
display_matrix(matrix_B,rowsB,colsB);
printf("\n\n");
display_matrix(matrix_result,rowsB,colsA);
}
else
{
printf("Check the dimensions of the matrices!\n");
exit(-1);
}
}
int **matrix_generator(int row, int col)
{
int i, j, **intMatrix;
intMatrix = (int **)malloc(sizeof(int *) * row);
srand(time(0));
for (i = 0; i < row; i++)
{
intMatrix[i] = (int *)malloc(sizeof(int *) * col);
for (j = 0;j<col;j++)
{
intMatrix[i][j]=rand()%10;
}
}
return intMatrix;
}
int **multiply_matrices(int **matrix_A,int **matrix_B,int rowsA, int colsA,int rowsB,int colsB)
{
int i, j, k, **resMatrix;
resMatrix = (int **)malloc(sizeof(int *) * rowsB);
for (i = 0; i < rowsA; i++)
{
resMatrix[i] = (int *)malloc(sizeof(int *) * colsA);
for (j = 0;j<colsB;j++)
{
for (k = 0; k < colsA; k++)
resMatrix[i][j] = resMatrix[i][j] + matrix_A[i][k] * matrix_B[k][j];
}
}
return resMatrix;
}
void display_matrix(int **matrix, int rows,int cols)
{
int i,j;
for (i = 0; i < rows; i = i + 1)
{
for (j = 0; j < cols; j = j + 1)
printf("%d ",matrix[i][j]);
printf("\n");
}
}
OUTPUT:
Enter the dimensions of Matrix A:
4
4
Enter the dimensions of Matrix B:
4
4
Matrix A:
8 7 8 4
9 8 3 9
1 2 0 4
6 0 2 3
Matrix B:
8 7 8 4
9 8 3 9
1 2 0 4
6 0 2 3
159 128 93 139
201 133 114 147
50 23 22 34
68 46 54 41
Can someone please help me understand where I'm going wrong? I have a pretty good idea that it's the matrix_generator() function but cannot seem to figure out what's wrong. Also, It's only multiplying square matrices, if the dimensions are different, like 4X5 and 5X4, I get a segmentation fault.
There are a few issues in your code:
1) You allocate memory incorrectly:
in multiply_matrices should be
resMatrix[i] = (int *)malloc(sizeof(int) * colsB);
and in matrix_generator
intMatrix[i] = (int *)malloc(sizeof(int) * col);
2) In main if you want to print matrix_result call
display_matrix(matrix_result,rowsA,colsB);
Dimensions of [rowsA,colsA] x [rowsB,colsB] is rowsA x colsB
3) malloc returns pointer to uninitialized memory, so you should set resMatrix elements to zero before summing
Content of 2-nd for loop in multiply_matrices should be
resMatrix[i][j] = 0;
for (k = 0; k < rowsB; k++) // CHANGED to rowsB
resMatrix[i][j] = resMatrix[i][j] + matrix_A[i][k] * matrix_B[k][j];
As pointed out in the comments: You need to seed the rand() function only once. Do srand(time(0)); at the start of your main() function and remove it from elsewhere.
Non-square matrices: There is a bug/typo in multiply_matrices
The line
for (k = 0; k < colsA; k++)
should be
for (k = 0; k < rowsA; k++)
Below is the program I tried.
I get the 2D array and print that array just after the all elements are scanned
like below
int main(void) {
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
int R, C;
scanf("%d %d", &R, &C);
int i[C][R];
for (int row = 0; row < R; row++) {
for (int column = 0; column < C; column++) {
int val = 0;
scanf("%d", &val);
i[row][column] = val;
}
}
for (int row = 0; row < R; row++) {
for (int column = 0; column < C; column++) {
printf("%d \t", i[row][column]);
}
printf("\n");
}
printf("RotatedMatrix\n");
return EXIT_SUCCESS;
}
I give the input as 3,4 indicating 3 rows and 4 columns so totally 12 elements
I give the input from 1 to 12 for matrix
But the output matrix looks like below
1 2 3 5
5 6 7 9
9 10 11 12
Instead of
1 2 3 4
5 6 7 8
9 10 11 12
The elements on last column is changed like above
I can't figure out what I am missing. It would be helpful if I get any help
It should be
int i[R][C];
instead of
int i[C][R];
I'm trying to create a 2d-array in bubble sort, arranged 25 numbers 5 by 5 in ascending order
my inputs
Enter 25 integers:
Input No.[0][0]: 4
Input No.[0][1]: 5
Input No.[0][2]: 8
Input No.[0][3]: 9
Input No.[0][4]: 4
Input No.[1][0]: 2
Input No.[1][1]: 1
Input No.[1][2]: 0
Input No.[1][3]: 2
Input No.[1][4]: 4
Input No.[2][0]: 6
Input No.[2][1]: 7
Input No.[2][2]: 4
Input No.[2][3]: 5
Input No.[2][4]: 5
Input No.[3][0]: 4
Input No.[3][1]: 8
Input No.[3][2]: 9
Input No.[3][3]: 1
Input No.[3][4]: 2
Input No.[4][0]: 4
Input No.[4][1]: 5
Input No.[4][2]: 2
Input No.[4][3]: 1
Input No.[4][4]: 9
my output shows
Ascending:
4 4 5 8 9
0 1 2 2 4
4 5 5 6 7
1 2 4 8 9
1 2 4 5 9
as you can see its not in proper arranged, it only arranged the 5 numbers each lines not the whole numbers
can anybody help arranged my integers like this
Ascending:
0 1 1 1 2
2 2 2 4 4
4 4 4 4 5
5 5 5 6 7
8 8 9 9 9
this is my code so far
int main(){
int rows = 5, cols = 5;
int arr[rows][cols];
int i,j,k,swap;
printf("Enter 25 integers:\n");
for(i = 0; i < rows; i++){
for(j = 0; j < cols; j++){
printf("Input No.[%d][%d]: ", i+0,j+0);
scanf("%d", &arr[i][j]);
}
}
for(k = 0; k < rows; k++){
for(i = 0 ; i < cols; i++){
for(j = i + 1; j < cols; j++){
if(arr[k][i] > arr[k][j]){
swap = arr[k][i];
arr[k][i] = arr[k][j];
arr[k][j] = swap;
}
}
}
}
printf("Ascending:\n");
for( i = 0 ; i < rows; i++){
for( j = 0 ; j < cols; j++){
printf("%3d", arr[i][j]);
}
printf("\n");
}
getch();
}
Improving on Ahmad's answer, I would like to add the following code (for shorting the table in ascending order):
#include <stdio.h>
#define COL 5
#define ROW 6
int main()
{
int temp, t, i, j;
int arr[ROW][COL]={30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
for(t=1; t<(ROW*COL); t++)
{
for(i=0; i<ROW; i++)
{
for(j=0; j<COL-1; j++)
{
if (arr[i][j]>arr[i][j+1])
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
}
for(i=0; i<ROW-1; i++)
{
if (arr[i][COL-1]>arr[i+1][0])
{
temp=arr[i][COL-1];
arr[i][COL-1]=arr[i+1][0];
arr[i+1][0]=temp;
}
}
}
for(i=0; i<ROW; i++)
{
printf("\n");
for(j=0; j<COL; j++)
printf("%3d", arr[i][j]);
}
return 0;
}
replace the input with your table and the definitions with the size of your given array and you're done.
output of the above when executed:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
void twoDimBubbleSort(int** arr, int row, int col) {
for (int i = 0; i < (row * col); ++i) {
for (int j = 0; j < (row * col) - 1; ++j) {
int cr = j / col; // current row
int cc = j % col; // current column
int nr = (j + 1) / col; // next item row
int nc = (j + 1) % col; // next item column
if (arr[cr][cc] > arr[nr][nc])
swap(&arr[cr][cc], &arr[nr][nc]); // any way you want to swap variables
}
}
}
You don't necessarily need to create a 1D array, you can consider your 2D array is a 1D array and transform coordinates when you set/get them.
Consider a structure point with x and y, and ARR_LEN is 5.
int from2Dto1D(point p){ return p.x+ p.y*ARR_LEN;}
Point from1Dto2D(int i){ Point p; p.x = i%ARR_LEN; p.y=i/ARR_LEN; return p;}
Now you can use the normal bubble sorting algorithm with a 1D index on 2D squares array, you just need to convert your index into 2 Point and access/switch data using these Point. (2 because you need a Point with index and a Point with index+1
Put all the array elements from 2-D array to 1-D array then
sort that 1-D array and then put 1-D array in the matrix format
Try this code ....works according to the above given logic
#include<stdio.h>
int main(){
int arr[5][5],l=0;
int result[25],k=0,i,j,temp;
arr[0][0]= 4;
arr[0][1]= 5;
arr[0][2]= 8;
arr[0][3]= 9;
arr[0][4]= 4;
arr[1][0]= 2;
arr[1][1]= 1;
arr[1][2]= 0;
arr[1][3]= 2;
arr[1][4]= 4;
arr[2][0]= 6;
arr[2][1]= 7;
arr[2][2]= 4;
arr[2][3]= 5;
arr[2][4]= 5;
arr[3][0]= 4;
arr[3][1]= 8;
arr[3][2]= 9;
arr[3][3]= 1;
arr[3][4]= 2;
arr[4][0]= 4;
arr[4][1]= 5;
arr[4][2]= 2;
arr[4][3]= 1;
arr[4][4]= 9;
//convert 2 D array in 1 D array
for(i=0;i<5;i++){
printf("\n");
for(j=0;j<5;j++){
printf(" %d",arr[i][j]);
result[k++]=arr[i][j];
}
}
// sort 1 D array
for(i=0;i<25;i++){
for(j=0;j<24;j++){
if(result[j] > result[j+1]){
temp=result[j];
result[j]=result[j+1];
result[j+1]=temp;
}
}
}
/*
for(i=0;i<25;i++){
printf("\n%d",result[i]);
}*/
// convert 1 D array to 2 D array
i=0;
l=0;k=0;
while(i<25){
for(j=0;j<5;j++){
arr[k][j]=result[l];
l++;
}
k++;
i=i+5;
}
//Print matrix i.e 2D array
for(i=0;i<5;i++){
printf("\n");
for(j=0;j<5;j++){
printf(" %d",arr[i][j]);
}
}
}
This works !
#define COL 5
#define ROW 2
int main(){
int temp ;
int arr[2][5]= {2,15,26,14,12,18,1,2,3,4 };
int arr2[10] = {0};
int index = 0 ;
for(int t = 0 ; t<50 ; t++ ){
for (int i =0 ; i < ROW ; i++){
for( int j = 0; j < 5-1 ; j++){
if (arr[i][j] > arr[i][j+1]){
temp = arr[i][j];
arr[i][j] = arr[i][j+1];
arr[i][j+1] = temp;
}
}
//checking for
for( int k = 0 ; k < ROW-1 ; k++){
if (arr[k][COL-1] > arr[k+1][0]){
temp = arr[k][COL-1];
arr[k][COL-1] = arr[k+1][0];
arr[k+1][0] = temp ;
}
}
//---------
}
}
return 0 ;
}
I am trying to generate all the subsets of a set in a non recursive manner. This is the code:
#include <stdio.h>
main() {
int no_of_element, no_of_subset, i, j, start, index, a[50], x;
printf("Enter the size of main set :");
scanf("%d", &no_of_element);
printf("Enter the elements of main set :");
for (x = 0; x < no_of_element; x++)
scanf("%d", &a[x]);
printf("The subsets are :\n");
for (no_of_subset = 1; no_of_subset <= no_of_element; no_of_subset++) {
for (start = 0; start <= no_of_element - no_of_subset; start++) {
if (no_of_subset == 1)
printf("%d\n", a[start]);
else {
index = start + no_of_subset - 1;
for (j = index; j < no_of_element; j++) {
for (i = start; i < index; i++) {
printf("%d\t", a[i]);
}
printf("%d\n", a[j]);
}
}
}
}
}
This is the output:
Enter the size of main set :4
Enter the elements of main set :1
2
3
4
The subsets are :
1
2
3
4
1 2
1 3
1 4
2 3
2 4
3 4
1 2 3
1 2 4
2 3 4
1 2 3 4
This code isn't generating the subset (1,3,4). Could someone please help me fix it ?
Just for fun, I dit it from scratch.
The trick is to let a counter go through all the possible subsets, each being a combination of its bits.
In case, use unsigned long int to handle sets of up to 64 elements:
#include <stdio.h>
void print_subset(int subset, int *set) {
int pos=0;
printf("Subset %d = ", subset);
while (subset) {
if (subset & 1) {
printf("%d ", set[pos]);
}
subset >>= 1;
pos++;
}
printf("\n");
}
int main()
{
int no_of_element,no_of_subset,x,a[50];
printf("Enter the size of main set :");
scanf("%d",&no_of_element);
printf("Enter the elements of main set :");
for(x=0;x<no_of_element;x++)
scanf("%d",&a[x]);
no_of_subset= (1 << no_of_element);
printf("There are %d subsets\n", no_of_subset);
for (; no_of_subset--;) {
print_subset(no_of_subset, a);
}
}
When run it produces
Enter the size of main set :4
Enter the elements of main set :1
2
3
4
There are 16 subsets
Subset 15 = 1 2 3 4
Subset 14 = 2 3 4
Subset 13 = 1 3 4
Subset 12 = 3 4
Subset 11 = 1 2 4
Subset 10 = 2 4
Subset 9 = 1 4
Subset 8 = 4
Subset 7 = 1 2 3
Subset 6 = 2 3
Subset 5 = 1 3
Subset 4 = 3
Subset 3 = 1 2
Subset 2 = 2
Subset 1 = 1
Subset 0 =
#include <stdio.h>
#include <stdlib.h>
void print(size_t n, int a[n]){
size_t i;
for(i=0; i < n; ++i){
if(i)
putchar(',');
printf("%d", a[i]);
}
putchar('\n');
}
void subset(size_t n, int a[n], size_t size){
int *out = malloc(size * sizeof(*out));
int *level = malloc((size+1)*sizeof(int));
int *index = malloc((size+1)*sizeof(int));
int sp = 0;
level[sp] = 0;
index[sp] = 0;
redo:
while(index[sp] < n){
out[level[sp]] = a[index[sp]];
level[sp+1] = level[sp] + 1;
index[sp+1] = index[sp] + 1;
if(level[++sp] == size){
print(size, out);
--sp;
} else
goto redo;//this means recursive call
++index[sp];
}
if(sp>0){
++index[--sp];
goto redo;
}
free(level);
free(index);
free(out);
}
int main(void){
int a[] = {1, 2, 3, 4};
size_t i, n = sizeof(a)/sizeof(*a);
for(i = 1; i <= n; ++i)
subset(n, a, i);
return 0;
}
result:
1
2
3
4
1,2
1,3
1,4
2,3
2,4
3,4
1,2,3
1,2,4
1,3,4
2,3,4
1,2,3,4