Last active
October 15, 2017 01:52
-
-
Save jialinhuang00/87d5752f89b0be1ee7cc2f414cfefdce to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/*----------------------------------------------------------------------------- | |
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]); |
This file contains hidden or 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
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