Skip to content

Instantly share code, notes, and snippets.

@liuwenzhuang
Last active March 15, 2018 08:26
Show Gist options
  • Save liuwenzhuang/9f27fd49dc76808ecb78c3cbc0e18795 to your computer and use it in GitHub Desktop.
Save liuwenzhuang/9f27fd49dc76808ecb78c3cbc0e18795 to your computer and use it in GitHub Desktop.
选择排序,每次遍历乱序区找出最小(大)值放入有序区,直至乱序区为空。Selection Sort, every loop to find the min/max value and put it into order domain until unorder domain is empty.
/**
* 选择排序,时间复杂度O(n^2),空间复杂度O(1)
* @param {Array} arr 需要进行排序的数组
* @return {Array} arr 排序完成后的数组
*/
function selectionSort(arr) {
if(Object.prototype.toString.call(arr) === "[object Array]") {
var len = arr.length;
var minIndex, temp;
for(var i=0; i<len-1; i++) {
minIndex = i;
for(var j=i+1; j<len; j++) {
if(arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
return arr;
} else {
return 'not array';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment