冒泡排序

225 阅读1分钟
let arr = [1, 9, 5, 0, 8, 3, 7, 6];
function sorts(arr) {
	let len = arr.length;
	for (let i = 0; i < len; i++) {
		for (let j = 0; j < len -i -1; j++) {
			if (arr[j] > arr[j+1]) {
				let temp = arr[j+1];
				arr[j+1]= arr[j];
				arr[j]= temp;
			}
		}
	}
	return arr;
}

  
console.log(sorts(arr))

算法原理:每次对相邻的两个元素进行比较,若前者大于后者则进行交换,如此一趟下来最后一趟的就是最大元素,重复以上的步骤,除了已经确定的元素