插入排序(C語言實現) 分類: 數據結構 2014-12-03 14:48 120人閱讀 評論(0) 收藏



    插入排序
    思想:1.從第二個數開始比較
                 2.若是比第一個數大,就排在右邊,不然,就在左邊,同時在和左邊的數一一比較






若是圖看懂了,接下來的代碼,將很是簡單理解
函數

 頭文件 sort.h
#include <stdio.h>

void Print(int* arr,int len)
{
    int i;
    for(i=0;i<len;i++)
    {
        printf("%d ",arr[i]);
    }
    printf("\n");
}

void Swap(int* a,int* b)
{
    *a=*a+*b;
    *b=*a-*b;
    *a=*a-*b;
}


主函數main

#include "sort.h"

void InsertSort(int* arr,int len);
int main(void)
{
    int arr[]={5,4,3,2,1};
    int len=sizeof(arr)/sizeof(int);
    Print(arr,len);
    InsertSort(arr,len);
    Print(arr,len);
    return 0;
}

void InsertSort(int* arr,int len)
{
    int temp,in,out;
    if(arr!=NULL)
    {
        for(out=1;out<len;out++)
        {
            temp=arr[out];  
            in=out;
            while(in>0 && arr[in-1]>temp)
            {
//                arr[in]=arr[in-1];
                Swap(&arr[in],&arr[in-1]); //交換兩個變量的值
                in--;
            }
//            arr[in]=temp;
        }
    }
}






版權聲明:本文爲博主原創文章,未經博主容許不得轉載。code

相關文章
相關標籤/搜索