Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Last active October 15, 2017 01:52
Show Gist options
  • Save jialinhuang00/87d5752f89b0be1ee7cc2f414cfefdce to your computer and use it in GitHub Desktop.
Save jialinhuang00/87d5752f89b0be1ee7cc2f414cfefdce to your computer and use it in GitHub Desktop.
/*-----------------------------------------------------------------------------
change, change, just keep changing like bubbles
the reference used at the second function is from UdemyCourse: LearningAlgorithmsInJavascriptFromScratch
-----------------------------------------------------------------------------*/
/*******************************************
在cs50 2016 week3時學到的Pseudocode
repeat until now swap
for I from 0 to n-2
if i’th and i+1’th elements out of order
swap them
*******************************************/
function bubbleSort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = arr.length; j > i; j--) {
if (arr[i] > arr[j]) {
// swapping
var tem = arr[i];
arr[i] = arr[j];
arr[j] = tem;
}
}
}
return arr;
}
bubbleSort([1, 7, 5, 3, 2, 4, 1.3, 10, 1, 3, 4, 42]);
function bubbleSort2(arr) {
for (var i = arr.length; i > 0; i--) {
for (var j = 0; j < i; j++) {
if (arr[j] > arr[i]) {
var tem = arr[i];
arr[i] = arr[j];
arr[j] = tem;
}
}
}
return arr;
}
bubbleSort2([1, 7, 5, 3, 2, 4, 1.3, 10, 1, 3, 4, 42]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment