버블 정렬
Array.prototype.bubbleSort = function() {
// console.log(this)
for (let i = 0; i < this.length - 1; i++) {
for(let j = 0;j<this.length -1 - i; j+=1){ // -1 可以用j+1来获取 - i是为了缩小循环节省时间
if(this[j] > this[j+1]){
const temp = this[j] // 存储j
this[j] = this[j+1] // 切换 j 和 j+1元素的位置
this[j+1] = temp; // j+1 = j
}
}
}
}
const arr = [ 5,4,3,2,1]
arr.bubbleSort()
console.log(arr)
두 개의 중첩 된 루프
시간 복잡도 O (n ^ 2)
정렬 선택
아이디어 선택 및 분류
배열에서 가장 작은 값을 찾아 선택하고 먼저 배치합니다.
그런 다음 두 번째로 작은 값을 찾아 선택하고 두 번째 위치에 배치합니다.
비유로 N-1 라운드를 수행하십시오.
Array.prototype.slectionSort = function() {
for (let i = 0; i < this.length - 1; i++) {
let indexMin = i // 等于i 是为了缩减循环,因为找的是最小的值 每一轮都是最小的
for(let j = i;j<this.length; j+=1){ // 等于i 是为了缩减循环, 这个循环是为了找到最小值的下标
if(this[j] < this[indexMin]){
indexMin = j
}
}
if( indexMin !== i){ //优化 避免最小值的下标和当前下标相等
const temp = this[i]; // 进行替换
this[i] = this[indexMin]
this[indexMin] = temp
}
}
}
const arr = [ 5,4,3,2,1]
arr.slectionSort()
console.log(arr)
두 개의 중첩 된 루프
시간 복잡도 O (n ^ 2)
삽입 정렬
삽입 정렬의 아이디어
두 번째 숫자부터 시작하여 앞으로 나아갑니다.
그의 삼촌 뒤에.
그리고 마지막 숫자에 대해서도 마찬가지입니다.
Array.prototype.insertionSotr = function() {
for(let i =1 ; i < this.length; i+=1){ // 拿数组的第二个元素和前一个对比 所以i =1
const temp = this[i] // 获取当前对比元素
let j = i; // 元素下标
while (j>0){
if(this[j-1] > temp){ // j-1 获取前一个元素的值 进行对比
this[j] = this[j-1] ; // 进行替换
}
else{
break; // 终止循环
}
j -= 1; //循环条件
}
this[j] = temp ; //进行插入
}
}
const arr = [ 5,4,3,2,1,6,9,8,7]
arr.insertionSotr()
console.log(arr)
두 개의 중첩 된 루프
시간 복잡도 O (n ^ 2)
병합 정렬
병합 및 정렬 아이디어
나누기 : 배열을 반으로 나누고 하위 배열을 개별 숫자로 나눌 때까지 반복적으로 "나누십시오".
결합 : 두 개의 숫자를 정렬 된 배열로 결합하고 모든 하위 배열이 완전한 배열로 결합 될 때까지 정렬 된 배열을 결합합니다.
두 개의 정렬 된 배열 결합
빈 배열 res를 만들어 최종 정렬 된 배열을 저장합니다. ,
정렬 된 두 배열의 헤드를 비교하면 더 작은 배열이 일치하고 res로 푸시됩니다.
두 배열에 여전히 값이 있으면 두 번째 단계를 반복합니다.
Array.prototype.mergeSort = function() {
const rec =(arr) =>{
if(arr.length === 1) {return arr} // 预防死循环 并返回数组
const mid = Math.floor(arr.length / 2) // 获取中间下标
const left = arr.slice(0,mid) // 获取左边数组
const right = arr.slice(mid,arr.length);// 右边的数组
const orderLeft = rec(left) // 分隔左数组 得到有序数组
const orderRight = rec(right) // 分隔右数组 得到有序数组
const res = [];
while(orderLeft.length || orderRight.length){
if(orderLeft.length && orderRight.length){
// 如果左边的对头 小于 右边对头 那么左边的出对 否则 右边出对 然后进入res
res.push(orderLeft[0] < orderRight[0] ? orderLeft.shift() : orderRight.shift())
}else if(orderLeft.length){ // 如果左边还有值
res.push(orderLeft.shift()) //那么不断的出对并进入数组
}else if(orderRight.length){ // 如果右边还有值
res.push(orderRight.shift()) //那么不断的出对并进入数组
}
}
return res
}
const res = rec(this)
res.forEach((n,i)=>{this[i] = n})
}
const arr = [ 5,4,3,2,1,6,9,8,7]
arr.mergeSort()
console.log(arr)
분의 시간 복잡도는 O (logN)입니다.
결합 된 시간 복잡도는 O (n)입니다.
시간 복잡도 O (n * logN)
\
빠른 정렬
파티션 : 어레이에서 "벤치 마크"를 임의로 선택합니다. 벤치 마크보다 작은 모든 요소는 벤치 마크 앞에 배치되고 벤치 마크보다 작은 요소는 벤치 마크 뒤에 배치됩니다.
재귀 : 벤치 마크 전후에 하위 배열을 재귀 적으로 분할합니다.
Array.prototype.quickSort = function() {
const rec =(arr) =>{
if(arr.length === 1){return arr}
// 分别存放 前后的数组
const left = []
const right = []
// 设置一个基准
const mid = arr[0]
//进行分区
for(let i =1; i<arr.length; i+=1){
if(arr[i] < mid){
left.push(arr[i])
}else{
right.push(arr[i])
}
}
return [...rec(left),mid,...rec(right)] //...用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中
}
const res = rec(this)
res.forEach((n,i)=>{this[i] = n})
}
const arr = [ 5,4,3,2,1,6,9,8,7]
arr.quickSort()
console.log(arr)
재귀의 시간 복잡도는 O (logN)
파티션 작업의 시간 복잡도는 O (n)
시간 복잡도 O (n * logN)
순차 검색
배열을 횡단합니다.
대상과 동일한 요소를 찾아 아래 첨자를 반환합니다.
순회 후 대상 값이 없으면 -1을 반환합니다.
Array.prototype.sequentialSearch = function(val){
for(let i=0;i<this.length;i+=1){
if(this[i] === item){
return i
}
}
return -1
}
const res = [1,2,3,4,5,6].sequentialSearch(2)
시간 복잡도 O (n)
이진 검색
배열의 중간 요소부터 시작하여 중간 요소가 대상 값이면 검색이 종료됩니다.
대상 값이 중간 요소보다 크거나 작 으면 중간 요소보다 크거나 작은 배열의 절반을 검색합니다.
Array.prototype.binarySearch = function(val) {
// * 二分搜索的数组是有序的
let low = 0;
let high = this.length -1;
while( low <= high){
const mid = Math.floor((low+high) / 2)
const elemnt = this[mid]
if(elemnt < val){
low = mid + 1
}
else if(elemnt > val){
high = mid - 1
}else {
return mid
}
}
return -1
}
const arr = [1,2,3,4,5].binarySearch(2)
console.log(arr)
시간 복잡도 O (logN)