选择排序
function createArr(num) {
let arr = new Array(num);
for (let i = 0; i < num; i++) {
arr[i] = Math.ceil(Math.random() * 10000);
}
return arr;
}
function selectSort(arr) {
console.time();
let min = 0; //存放最小值
let minIndex = 0; //寻找最小值的下标
for (let i = 0; i < arr.length - 1; i++) {
min = arr[i];
minIndex = i;
for (let j = i + 1; j < arr.length; j++) {
if (min > arr[j]) {
min = arr[j];
minIndex = j;
}
}
if (i !== minIndex) {
//若有比第i个数小的数则交换
arr[minIndex] = arr[i];
arr[i] = min;
}
}
console.timeEnd();
}
let targetArr = createArr(80000);
selectSort(targetArr);
归并排序
function createArr(num) {
let arr = new Array(num)
for (let i = 0; i < num; i++) {
arr[i] = Math.ceil(Math.random() * 10000);
}
return arr
}
function mergeSort(arr) {
console.time()
_mergeSort(0, arr.length - 1)
function _mergeSort(left, right) {
if (left < right) { //假如当前数组长度大于1,有分解空间
let mid = Math.floor((left + right) / 2)
_mergeSort(left, mid)
_mergeSort(mid + 1, right)
// 这个地方代表left到mid的顺序已经排好 mid+1到right的顺序排好
let tempArr = new Array(right - left + 1)
let i = left
let j = mid + 1
let t = 0
while (i <= mid && j <= right) { //当其中一个有序段已经复制完毕,跳出循环,剩下的数据均为比该序列的数大
if (arr[i] <= arr[j]) {
tempArr[t] = arr[i]
i++
} else {
tempArr[t] = arr[j]
j++
}
t++
}
while (i <= mid) { //左序列剩余数加到数组
tempArr[t] = arr[i]
t++
i++
}
while (j <= right) { //右边序列剩余数加到数组
tempArr[t] = arr[j]
t++
j++
}
let tempLeft = left //把新数组的数据复制到原数组上
while (tempLeft <= right) {
arr[tempLeft] = tempArr[tempLeft - left]
tempLeft++
}
}
}
console.timeEnd()
}
let arr = createArr(80000)
mergeSort(arr)
基数排序
function createArr(num) {
let arr = new Array(num)
for (let i = 0; i < num; i++) {
arr[i] = Math.ceil(Math.random() * 10000);
}
return arr
}
function radixSort(arr, size) { //size代表数字的最大位数
console.time()
let bucket = new Array(10) //创建十个桶,代表数位0到9
let bucketCount = new Array(10) //记录每个桶里面有多少数据
for (let i = 0; i < 10; i++) {
bucket[i] = new Array(arr.length)
bucketCount[i] = 0
}
for (let i = 0; i < size; i++) {
let divisor = Math.pow(10, i )
let base = Math.pow(10, i+1 ) //用这个基取模,出来除以divisor,得出的值的整数部分就是第i+1位的数
for (let j = 0; j < arr.length; j++) { //根据i+1位数放进桶内
let index=Math.floor(arr[j] % base/divisor)
bucket[index][bucketCount[index]] = arr[j] //假设第i+1位数是1,代表第1个桶添加一个数进去,同时这个桶计数加1
bucketCount[index]++
}
let count=0
for (let j in bucketCount) { //把桶里的数复制到原数组
for (let index=0;index<bucketCount[j];index++){
arr[count]=bucket[j][index]
count++
}
bucketCount[j]=0 //归零,桶里的数已经复制到数组里面,桶内的逻辑空间为0
}
}
console.timeEnd()
}
let arr=createArr(80000)
radixSort(arr,4)