Jump space (list) Selection Sort sorting (selection sort), insertion sort (insertion sort)

Jump space (list) Selection Sort sorting (selection sort), insertion sort (insertion sort)

Select sorting (selection sort)

Algorithm principle: There is a basket of apples, first pick the largest one on the end, then jump out of a basket the rest of the big one, the biggest on the front just come out, and so on, and finally the good order .

Code:

//从起始于位置p的n个元素中选出最大者,所以n>1
template<typename T>
ListNode<T>* List<T>::selectMax(ListNode<T>* p, int n){

  ListNode<T>* max = p;
  while(1 < n--){
    if((p = p->succ)->data >= max->data) max = p;
  }

  return max;
}

//对从p开始的连续n个元素做选择排序,n > 1
template<typename T>
void List<T>::selectionSort(ListNode<T>* p, int n){

  ListNode<T>* head = p->pred;
  ListNode<T>* tail = p;

  for(int i = 0; i < n; ++i)  tail = tail->succ;

  while(1 < n){
    ListNode<T>* node = selectMax(head->succ, n--);

    //调整这个节点的前后节点
    node->pred->succ = node->succ;
    node->succ->pred = node->pred;

    //把卸下来的节点加到最后一个元素的前面
    //前进线路
    tail->pred->succ = node;
    node->succ = tail;
    //后退路线
    node->pred = tail->pred;
    tail->pred = node;

    tail = node;
  }
}

Insertion sort (insertion sort)

Algorithm principle: when playing poker or playing mahjong, catch after each card, based on his cards, Bazhua come this card is inserted into the proper order, each draw a card, insert once, all complete grasp after the order also lined up.

Code:

//在p的前n个前驱中,查找不大于e的最后者
template<typename T>
ListNode<T>* List<T>::search(const T& e, int n, ListNode<T>* p){

  while(0 < n--){
    if(p->pred->data <= e) return p->pred;
    p = p->pred;
  }

  return p;
}

//对从p开始的连续n个元素做选择排序
template<typename T>
void List<T>::insertionSort(ListNode<T>* p, int n){

  for(int r = 0; r < n; r++){
    if(r == 0) {
      p = p->succ;
      continue;
    }
    ListNode<T>* node = search(p->data, r, p->pred);
    auto tmp = p->succ;

    //删除p节点
    p->pred->succ = p->succ;
    p->succ->pred = p->pred;

    //在node节点后面插入p节点
    p->succ = node->succ;//设定p的后驱
    node->succ->pred = p;//设定p的后驱的前驱

    node->succ = p;//设定p的前驱的后驱
    p->pred = node;//设定p的前驱

    p = tmp;
  }
}

c / c ++ mutual learning QQ group: 877 684 253

I micro letter: xiaoshitou5854

Guess you like

Origin www.cnblogs.com/xiaoshiwang/p/11697648.html