TG Telegram Group & Channel
CodeRoll | Frontend | United States America (US)
Create: Update:

👩‍💻👩‍💻 Как выглядит алгоритм гномьей сортировки на JavaScript?

Алгоритм находит первое место, где два соседних элемента стоят в неправильном порядке и меняет их местами



const gnomeSort = (arr: number[]): number[] => {
if (arr.length <= 1) {
return arr
}

let i: number = 1

while (i < arr.length) {
if (arr[i - 1] <= arr[i]) {
i++ //increment index if sub-array[0:i] already sorted
} else {
;[arr[i], arr[i - 1]] = [arr[i - 1], arr[i]] //swapping two numbers
i = Math.max(1, i - 1) //go back to the previous index to check the swapped number
}
}
return arr
}


Coderoll | Frontend

👩‍💻👩‍💻 Как выглядит алгоритм гномьей сортировки на JavaScript?

Алгоритм находит первое место, где два соседних элемента стоят в неправильном порядке и меняет их местами



const gnomeSort = (arr: number[]): number[] => {
if (arr.length <= 1) {
return arr
}

let i: number = 1

while (i < arr.length) {
if (arr[i - 1] <= arr[i]) {
i++ //increment index if sub-array[0:i] already sorted
} else {
;[arr[i], arr[i - 1]] = [arr[i - 1], arr[i]] //swapping two numbers
i = Math.max(1, i - 1) //go back to the previous index to check the swapped number
}
}
return arr
}


Coderoll | Frontend
Please open Telegram to view this post
VIEW IN TELEGRAM
1


>>Click here to continue<<

CodeRoll | Frontend




Share with your best friend
VIEW MORE

United States America Popular Telegram Group (US)