常见的七种排序算法(插入排序—直接插入排序和希尔排序)

选择排序—选择排序和堆排序:
https://blog.csdn.net/qq_37941471/article/details/80372153
这里写图片描述

算法之间 时间复杂度.空间复杂度.稳定性的比较:

这里写图片描述

ps:希尔排序,当N大时,平均的时间复杂度,大约在N^1.25–1.6N^1.25之间。


直接排序:

  • 直接插入排序
  • 希尔排序

直接插入排序 :

思想:将数组中的所有元素依次和前面的已经排好序的元素相比较(依次),如果选择的元素比已排序的元素小,则交换,直到全部元素都比较过。

这里写图片描述

代码实现:

Sort.h:

#pragma once

#include <iostream>
using namespace std;

#include <assert.h>


//直接插入排序
 void InsertSort (int* a,size_t n)
 {
     assert(a);
     for(size_t i = 1;i < n; ++i)//用end的位置控制边界
     {
         //单趟排序
         int end = i - 1 ;
         int tmp = a[i];
         while( end >= 0 )//循环继续条件
         {
             if( a[end] > tmp )
             {
                 a[end+1] = a[end];
                 --end;
             }
             else
                 break;
         }
         a[end+1] = tmp;
     }
 }

test.cpp :

#include "Sort.h"

 void Print(int a[],int len)
{
    for(int i = 0; i < len; ++i)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

 void test()
 {
     //升序排序
     int a [] = {2,5,7,6,12,4,3,9,0};
     int len = sizeof(a)/sizeof(a[0]);
     cout<<"before sort :";
     Print(a,len);

     InsertSort(a,len);
     cout<<"after sort :";
     Print(a,len);

 }
int main ()
{
    test();
    return 0;
}

希尔排序 :

思想:希尔排序也称缩小增量排序;希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序,随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时(用gap = gap/3+1 控制),保证了最后一次进行直接插入排序,算法终止。(其中直接插入排序是希尔排序gap=1的特例)另外,gap越大,值越大的容易到最后面,但是不太接近有序。—— 一般gap不要超过数组大小的一半

这里写图片描述

代码实现:

void ShellSort(int* a,size_t n)
 {
     assert(a);
     //1. gap > 1 预排序
     //2. gap == 1 直接插入排序
     //3. gap = gap/3 + 1; 保证最后一次排序是直接插入排序

     int gap = n;
     while ( gap > 1 )
     {
         gap = gap/3+1;
         //单趟排序
         for(size_t i = 0;i < n-gap; ++i)
         {
             int end = i;
             int tmp = a[end+gap];
             while( end >= 0 && a[end] > tmp )
             {
                 a[end+gap] = a[end];
                 end -= gap;
             }
             a[end+gap] = tmp;
         }
     }
 }

猜你喜欢

转载自blog.csdn.net/qq_37941471/article/details/80358741
今日推荐