1 //1. 冒泡排序 2 var bubbleSort = function(arr) { 3 for (var i = 0; i < arr.length; i++) { 4 var flag = true; 5 for (var j = 0; j < arr.length - i - 1; j++) { 6 if (arr[j] > arr[j + 1]) { 7 flag = false; 8 arraySwap(arr, j, j + 1); 9 } 10 } 11 if (flag) { 12 break; 13 } 14 } 15 return arr; 16 }; 17 18 //2. 选择排序 19 var selectionSort = function(arr) { 20 for (var i = 1; i < arr.length - 1; i++) { 21 var min = arr[i], 22 minIndex = i; 23 for (var j = i + 1; j < arr.length; j++) { 24 if (arr[j] < min) { 25 min = arr[j]; 26 minIndex = j; 27 } 28 } 29 arraySwap(arr, i, minIndex); 30 } 31 return arr; 32 }; 33 34 //3. 插入排序 35 var insertionSort = function(arr) { 36 for (var i = 1; i < arr.length; i++) { 37 var temp = arr[i], 38 j = i - 1; 39 while (temp < arr[j] && j > -1) { 40 arr[j + 1] = arr[j]; 41 j--; 42 } 43 arr[j + 1] = temp; 44 } 45 return arr; 46 }; 47 48 //4. 快速排序 49 var quickSort = function(arr, start, end) { 50 if (start >= end) { 51 return arr; 52 } 53 var index = partition(arr, start, end); 54 quickSort(arr, start, index - 1); 55 quickSort(arr, index + 1, end); 56 return arr; 57 }; 58 59 var partition = function(arr, start, end) { 60 var temp = arr[start]; 61 62 while (start < end) { 63 while (start < end && arr[end] >= temp) { 64 end--; 65 } 66 arr[start] = arr[end]; 67 68 while (start < end && arr[start] <= temp) { 69 start++; 70 } 71 arr[end] = arr[start]; 72 } 73 74 arr[start] = temp; 75 return start; 76 };
原文:http://www.cnblogs.com/huoteng/p/5005825.html