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))
CodePudding user response:
You need to use a replace method on array values. See this for reference: Replace string in javascript array
CodePudding user response:
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(n²)
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(n²).
* As we iterate n times over (n - i) items.
* T(n) = Sum{from 0 to n}[n * (n-i)] = (n 1) * n = n² n = O(n²)
* @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; }