# Count no. of columns that are not sorted in increasing order in C++

We are given an array of strings each of the same length. The goal is to find columns, ( matrix of strings ) that are not sorted in increasing order. For example, each first character in string is compared with the first character of the next string and so on till the last string. If they are not in increasing order, increase the count. Do this for all second characters, then third characters of all strings and so on till the last character.

## Input

Arr[]= { “abc”, “bcd”, “def” }

## Output

Count of columns: 0

Explanation − for each column,

Column 1: character at index 0 : a<b<d

Column 2: character at index 1 : b<c<e

Column 3: character at index 2 : c<d<f

All corresponding characters in the column are sorted in increasing order.

## Input

Arr[]= { “dbd”, “faf”, “eeg” }

## Output

Count of columns: 2

Explanation − for each column,

Column 1 − character at index 0 : d<f>g

Column 2 − character at index 1 : b>a<e

Column 3 − character at index 2 : d<f<g

Column 1 and 2 have characters without increasing order. Count=2

## Approach used in the below program is as follows

• Character array arr[][] is used to store strings of the same length.

• Function countCols(char str[3][4],int n,int len) takes a string array, no. of strings in it and length of each string as input and returns the count of columns that are not in increasing order.

• Initialize count with 0.

• Col is used to represent the current column. ( common index for all strings ).

• Travers each string simultaneously starting from the first index using a for loop till the length of string ( same length for all ).

• Here each string is of 3 characters so we compare str[col][j]>str[col+1][j-1] || str[col+1][j]>str[col+2][j-1]. If any condition is true, increase count.

• After the end of for loop return the result present in count.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int countCols(char str[3][4],int n,int len){
int i,j;
int count=0;
int col=0;
for(j=0;j<len;j++){
if(str[col][j]>str[col+1][j-1] || str[col+1][j]>str[col+2][j-1] )
count++;
}
return count;
}
int main(){
char arr[3][4]={"abc", "daf", "ghi"};
cout<<"\nColumns that are not sorted:"<<countCols(arr,3,3);
return 0;
}

## Output

Columns that are not sorted:2

Updated on: 28-Jul-2020

144 Views