zoukankan      html  css  js  c++  java
  • 数据结构与算法——插入类排序(直接插入排序,希尔排序)

    一、直接插入排序

    对于一个有序的序列。不断将后面的元素插入前面的有序序列。保持序列继续有序。

    对于直接插入排序的思路:将要排序的元素保存。然后逐个和其前面的元素进行比較。假设前面的元素比其大,则将前面的元素后移一个。

    时间复杂度为n*n

    void insert_sort(int a[],int n)
    {
       int i,j;
       int temp;
       for(i=1;i<n;i++)
       {
          temp = a[i];
    	  j=i-1;
    	  while((j>=0)&& (temp<a[j]))
    	  {
    	    a[j+1] = a[j];
    		j--;
    	  }
       
    	  a[j+1] = temp;
       }
    
       
    }


    二、希尔排序

    把整个序列切割成为若干个子序列。分别进行插入排序。待整个序列“基本有序”。再对全体序列进行排序。

    #include <stdio.h>
    
    void shell_sort(int a[],int n)
    {
    	int i,j,k,temp;
       //选择间隔为每次都除以2,取整数
    	for(i=n/2;i>0;i=i/2)  //i为间隔
    	{
    	     for(j=i;j<n;j++)
    		 {
               temp = a[j];
    		   for(k=j-i;(k>=0)&&(temp<a[k]);k=k-i)
    		   {
    		      a[k+i] = a[k];
    		   
    		   }
                 a[k+i] = temp;
    		 }
    	}
    
    	for(i=0;i<n;i++)
    	{
    	  printf("%d,",a[i]);
    	}
    
    }
    
    
    
    void main()
    {
        int a[] = {5,6,2,9,3,1,77,22,17};
    	int n =9;
    	shell_sort(a,n);
    
    
    }



  • 相关阅读:
    javascript实战演练,制作新按钮,‘新窗口打开网站’,点击打开新窗
    P1332 血色先锋队
    P4643 [国家集训队]阿狸和桃子的游戏
    T149876 公约数
    P1462 通往奥格瑞玛的道路
    P1083 借教室
    Tribles UVA
    Fence Repair POJ
    Crossing Rivers
    关于一轮
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/7160357.html
Copyright © 2011-2022 走看看