插入排序

升序排

对数组进行插入排序

void insert_sort(int* ar, int n)
{
    int key;
    for (int j = 1; j < n; j++)
    {
        key = ar[j];  //保存待排数据
        int i;
        for (i = j - 1; i >= 0; i--)
        {
            if (ar[i] > key)  //比待排数据大,右移
                ar[i + 1] = ar[i];
        }
        ar[i + 1] = key;  //插入待排数据
    }
}

对线性表进行插入排序

void insert_sort_ll(LinkList& list)
{
      if(head->next)
      {
          LinkList* last = head->next, *current = last->next; *in=head;
           while(current)
           {
                for(in = head; in!=last; in = in->next)
                {
                    if(current->data < in->next)
                     {
                          last->next = current->next;
                          current->next = in->last;
                          in->last = current;
                          break;
                     }
                }
                current = last->next;
           }
      }   
}

你可能感兴趣的:(插入排序)