小奋斗 - 轻松学习从此开始!
IT小奋斗群 QQ群:62017228

JavaScript中的排序(冒泡排序、选择排序、插入排序、希尔排序)

<script>
		//1. 冒泡排序
		function bubbleSort(arr) {
			var len = arr.length;
			for (var i = 0; i < len; i++) {
				for (var j = 0; j < len -1 - i; j++) {
					if (arr[j] > arr[j + 1]) {
						var temp = arr[j + 1];
						arr[j + 1] = arr[j];
						arr[j] = temp;
					}
				}
			}
			return arr;
		}
		var arr = [1,22,33,23,22,21,44,33];
		console.log(bubbleSort(arr));
		//2. 选择排序
		function selectionSort(arr) {
			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;
		}
		console.log(selectionSort(arr));
		//3. 插入排序
		function insertionSort(array) {
		    if (Object.prototype.toString.call(array).slice(8, -1) === 'Array') {
		        for (var i = 1; i < array.length; i++) {
		            var key = array[i];
		            var j = i - 1;
		            while (j >= 0 && array[j] > key) {
		                array[j + 1] = array[j];
		                j--;
		            }
		            array[j + 1] = key;
		        }
		        return array;
		    }
		}
		//4. 希尔排序
		function shellSort(arr) {
		    var len = arr.length,
		        temp,
		        gap = 1;
		    while(gap < len/5) {          //动态定义间隔序列
		        gap =gap*5+1;
		    }
		    for (gap; gap > 0; gap = Math.floor(gap/5)) {
		        for (var i = gap; i < len; i++) {
		            temp = arr[i];
		            for (var j = i-gap; j >= 0 && arr[j] > temp; j-=gap) {
		                arr[j+gap] = arr[j];
		            }
		            arr[j+gap] = temp;
		        }
		    }
		    return arr;
		}
	</script>

  

我来评几句
登录后评论

已发表评论数(0)