0

I'm trying to learn how functions work in JS. This function should order the string, but the result is equal to the string himself. what do I do wrong?

a = "awbc"
function f(str) {
 let temporary
 for (i = 0; i < a.length; i++) {
 for (j = 0; j < a.length; j++) {
 if (a[j] < a[j + 1]) {
 temporary = a[j]
 a[j] = a[j + 1]
 a[j + 1] = temporary
 }
 }
 }
 return a
}
console.log(f(a))

depperm
10.8k4 gold badges46 silver badges68 bronze badges
asked May 5, 2022 at 14:29
2
  • 2
    Strings are immutable; you cannot change them as if they were arrays. You can instead turn a string into an array, sort it (probably with .sort() instead of a home-made function) and then join the array back into a string. Commented May 5, 2022 at 14:31
  • wanted to answer with the same content) Commented May 5, 2022 at 14:35

2 Answers 2

0

You need to use a replace method on array values. See this for reference: Replace string in javascript array

answered May 5, 2022 at 14:39
Sign up to request clarification or add additional context in comments.

Comments

0

Strings are immutable

As already pointed out by Pointy (edit: believe it or not, no pun intended) in the comments, strings are immutable and cannot be changed. But what you can do is create one separate string for each character in your string and put that in an array using the split() method. Then you can sort that array and when it is sorted use join() to create another string consisting of those characters in sorted order.

Your bubbleSort() implementation

First of all the algorithm you are trying to implement is called bubble sort and is one of the easy but unfortunately slow sorting algorithms as it takes O(n2) in best, average and worst case runtime while good algorithms like merge sort only take O(n * log n).

Nevertheless, if you want to sort using bubbleSort() you need to make some changes to your code. You are sorting in descending order therefore in every iteration of the outer loop the biggest value will be moved to the left-most position. Therefore in the next iteration you need to find the next biggest value and move it to the now left-most position. No need to check for all elements again as we already know that the left-most element is the biggest. Therefore start your inner loop at position i instead of 0. This will change nothing in the time complexity in big-O notation but will nevertheless improve the performance significantly.

Iteration i of outer loop temporary
0 [ a,w,b,c ]
1 [ w,b,c,a ]
2 [ w,c,b,a ]
3 [ w,c,b,a ]

Also you are using a function in order to encapsulate functionality so you should not modify global variables within it. Use the str parameter you pass to it instead of a.

Last but not least you have this line temporary = a[j] but temporary should hold your array of individual character strings which you will destroy with this assignment. Create a new variable temp instead to do the swap.

Here an implementation of bubbleSort() with all those issues addressed.

/**
 * Bubble sort algorithm which has sorts characters in a string in descending order.
 * Best/ average and worst case runtime of bubble sort is O(n2).
 * As we iterate n times over (n - i) items.
 * T(n) = Sum{from 0 to n}[n * (n-i)] = (n + 1) * n = n2 + n = O(n2)
 * @param {string} str string
 * @returns 
 */
function bubbleSort(str) {
 const temporary = str.split("");
 // temporary now contains every single character
 console.log("After split:", temporary);
 // in each iteration of the outer loop the "biggest" letter will be sorted to the front
 for (let i = 0; i < temporary.length; i++) {
 // you need to start from i as otherwise you will be moving already sorted letters (as they are moved to the front)
 for (let j = i; j < temporary.length - 1; j++) {
 if (temporary[j] < temporary[j + 1]) {
 // you need other variable here, otherwise you will override temporary
 const temp = temporary[j];
 temporary[j] = temporary[j + 1];
 temporary[j + 1] = temp;
 }
 }
 }
 // now join characters back together to a string
 console.log("After sorting: ", temporary);
 return temporary.join("");
}
console.log(bubbleSort("awbc"));
console.log(bubbleSort("another _string with &)8 w?ird chars"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

answered May 5, 2022 at 15:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.