Skip to content

Instantly share code, notes, and snippets.

@VivienAdnot
Created May 24, 2017 10:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save VivienAdnot/16c475f619ee3cf4bed63b15cc254f29 to your computer and use it in GitHub Desktop.
Save VivienAdnot/16c475f619ee3cf4bed63b15cc254f29 to your computer and use it in GitHub Desktop.
bubble sort implementation in typescript
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;
}
@mahdi-hajian
Copy link

What is "array = array.slice();"
Why am I using this?
If I do not use this, what happens?

@Mytsu
Copy link

Mytsu commented Feb 12, 2019

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.

@y3v4psypl
Copy link

y3v4psypl commented Jul 27, 2022

It can be easily done with spread operator (ES6).
array = […array]

@Niziol
Copy link

Niziol commented Feb 21, 2023

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++)

@mat30k
Copy link

mat30k commented May 1, 2023

Line 2 is not necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment