Created
May 24, 2017 10:59
-
-
Save VivienAdnot/16c475f619ee3cf4bed63b15cc254f29 to your computer and use it in GitHub Desktop.
bubble sort implementation in typescript
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
export function bubbleSort(array: number[]): number[] { | |
array = array.slice(); // creates a copy of the array | |
for(let i = 0; i < array.length; i++) { | |
for(let j = 0; j < array.length - 1; j++) { | |
if(array[j] > array[j + 1]) { | |
let swap = array[j]; | |
array[j] = array[j + 1]; | |
array[j + 1] = swap; | |
} | |
} | |
} | |
return array; | |
} |
What is "array = array.slice();"
Why am I using this?
If I do not use this, what happens?
slice()
without parameters returns the array itself, an easy way to copy the data. slice()
accepts two parameters: the value that starts the slice you want and the value that finishes the slice.
It can be easily done with spread operator (ES6).
array = […array]
You can also add - i
to the second loop so that the sorting algorithm doesn't consider sorted elements, because in each iteration of the i
loop we are guaranteed to have i
of sorted elements.
It will look like this:
for(let j = 0; j < array.length - i- 1; j++)
Line 2 is not necessary.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is "array = array.slice();"
Why am I using this?
If I do not use this, what happens?