Last active
April 10, 2023 13:50
-
-
Save mdibrahimk48/08a39dadd47725c03e21915cd4dde84a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UV-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Sorting string using recursive sort algorithm</title> | |
<!-- Made by Md. Ibrahim Khalil --> | |
</head> | |
<body> | |
<script> | |
const input = prompt("Please Enter Your Name: "); | |
const nameUpperCaseArray = input | |
.split("") | |
.join("") | |
.toUpperCase() | |
.split(""); | |
printArry("Your name (Input): ", nameUpperCaseArray); | |
recursiveSelectionSort(nameUpperCaseArray); | |
printArry("Name after sorting (Output): ", nameUpperCaseArray); | |
printObject("Char count (Output): ", getCountChar(nameUpperCaseArray)); | |
//Defining a recursiveSelectionSort function that takes an array and its length as input parameters | |
function recursiveSelectionSort(arr, n = arr.length) { | |
if (n <= 1) { | |
return arr; | |
} | |
let maxIndex = 0; | |
for (let i = 1; i < n; i++) { | |
if (arr[i] > arr[maxIndex]) { | |
maxIndex = i; | |
} | |
} | |
//Swaps the maximum element with the last element of the array. | |
swap(arr, maxIndex, n - 1); | |
recursiveSelectionSort(arr, n - 1); | |
return arr; | |
} | |
//The function returns the sorted array | |
function swap(arr, i, j) { | |
const temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} | |
//Printing Function | |
function printObject(message, object) { | |
const arr = Object.keys(object); | |
document.write(message); | |
for (let i = 0; i < arr.length; i++) { | |
document.write(arr[i] + " = " + object[arr[i]] + " "); | |
} | |
document.write(" <br>"); | |
} | |
//For Printing Char | |
function printArry(message, arr) { | |
document.write(message); | |
for (let i = 0; i < arr.length; i++) { | |
document.write(arr[i] + " "); | |
} | |
document.write(" <br>"); | |
} | |
//For Char Counting | |
function getCountChar(arr) { | |
return arr.reduce((acc, cur) => { | |
if (acc[cur]) { | |
acc[cur] += 1; | |
return acc; | |
} | |
return { | |
...acc, | |
[cur]: 1, | |
}; | |
}, {}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment