Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check if a string is sorted in JavaScript
We are required to write a JavaScript function that takes in a string and checks whether it is sorted or not.
A string is considered sorted if its characters are arranged in either ascending or descending order. For example:
isSorted('adefgjmxz') // true (ascending)
isSorted('zxmfdba') // true (descending)
isSorted('dsfdsfva') // false (mixed order)
Method 1: Character by Character Comparison
This approach compares adjacent characters and tracks whether the string is ascending or descending:
const str = 'abdfhlmxz';
const findDiff = (a, b) => a.charCodeAt(0) - b.charCodeAt(0);
const isStringSorted = (str = '') => {
if(str.length < 2){
return true;
}
let res = '';
for(let i = 0; i < str.length-1; i++){
if(findDiff(str[i+1], str[i]) > 0){
res += 'u'; // ascending
} else if(findDiff(str[i+1], str[i]) < 0){
res += 'd'; // descending
}
// If both ascending and descending found, not sorted
if(res.includes('u') && res.includes('d')){
return false;
}
}
return true;
};
console.log(isStringSorted(str));
console.log(isStringSorted('zxmfdba'));
console.log(isStringSorted('dsfdsfva'));
true true false
Method 2: Simple Direction Tracking
A cleaner approach that directly tracks the direction of sorting:
const isStringSorted = (str) => {
if (str.length <= 1) return true;
let ascending = null; // null = unknown, true = ascending, false = descending
for (let i = 0; i < str.length - 1; i++) {
if (str[i] < str[i + 1]) {
if (ascending === false) return false; // was descending
ascending = true;
} else if (str[i] > str[i + 1]) {
if (ascending === true) return false; // was ascending
ascending = false;
}
// Equal characters don't change direction
}
return true;
};
// Test cases
console.log(isStringSorted('abc')); // true
console.log(isStringSorted('cba')); // true
console.log(isStringSorted('acb')); // false
console.log(isStringSorted('aab')); // true (ascending with duplicates)
true true false true
Comparison
| Method | Readability | Performance | Handles Duplicates |
|---|---|---|---|
| Character Code Comparison | Complex | O(n) | Yes |
| Direction Tracking | Simple | O(n) | Yes |
Key Points
Both methods handle edge cases like single characters and duplicate characters correctly. The direction tracking method is more readable and easier to understand.
Conclusion
Use the direction tracking approach for better code clarity. Both methods efficiently determine if a string is sorted in O(n) time complexity.
Advertisements
