Fork me on GitHub

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

Coding Poineer

顺序数据结构~~排序算法

快速排序

function quickSort(arr){
  let len = arr.length
  // 这里长度小于3,直接内置sort排序了
  if(len <= 2) return arr.sort() 
  let low = 0
  let high = len-1
  let cur = arr[0]
  let temp = 0
  while(high > low){
    while(high > low && arr[low+1] <= cur ){
      arr[low] = arr[low+1]
      low += 1
    }
    while(high > low && arr[high] > cur){
      high -= 1
    }
    if(low<high){
      temp = arr[low+1]
      arr[low++] = arr[high]
      arr[high--] = temp
    }
  }
  arr[low] = cur
  return quickSort(arr.slice(0,low+1)).concat(quickSort(arr.slice(low+1,len)))
}

quickSort([1,3,5,2,2])

插入排序:

function insertSort(arr){
  let cur ;
  let insert;
  for(let i = 1 ; i < arr.length ; i++){
    cur = arr[i]
    insert = i-1
    while(arr[insert] > cur){insert -= 1}
//     for(let j = i ; j >insert+1 ;j-- ){
//       arr[j] = arr[j-1]
//     }
    // js内置API简略写法
    // 简单插入排序
    arr.copyWithin(insert+2,insert+1,i)
    arr[insert+1] = cur
  }
  return	arr
}

判断一个链表中是否有环:

function ListNode(x){
   this.val = x;
   this.next = null;
}
function detectCycle( head ) {
  	if(!head ) return null
    while(head){
      var len = head.val.length
			if(!head.sign) head.sign = 'visited'
      else {
        delete head.sign
        return head
      }
      head = head.next
    }
  	return null 
}
posted @ 2020-11-09 14:01  365/24/60  阅读(62)  评论(0编辑  收藏  举报