C語言:歸併排序

來源:互聯網
上載者:User

標籤:turn   c語言   sort   排序   pre   總結   color   class   body   

歸併排序(C語言)。

先上代碼,理論會後面一起總結。

1. 遞迴

 

2. 非遞迴

#include <stdio.h>#include <stdlib.h>#include <string.h>void merge_sort(int* arr, int length){    int step = 1; //區間步長    int l[length], r[length]; //gcc, 兩個臨時數組,分別表示待歸併的兩個區間    //int l[100], r[100]; //vc    while(step < length)    {        int startloc = 0; //歸併區間的開始下標        while(startloc < length - step)        {            //歸            int len_l, len_r; //左右待歸併區間的長度            len_l = len_r = step;            memcpy(l, arr + startloc, sizeof(int) * len_l);            if(startloc + 2 * step > length)            {                len_r = length - startloc - step;            }            memcpy(r, arr + startloc + step, sizeof(int) * len_r);            //並            int i = 0, j = 0, k = startloc;            while(i < len_l && j < len_r)            {                arr[k++] = l[i] < r[j] ? l[i++] : r[j++];            }            while(i < len_l)            {                arr[k++] = l[i++];            }            startloc += 2 * step;        }        step *= 2;    }}int main(){    int arr[11] = {-1, 2, 4, -12, 4, 0, 0, 12, 23, -4, 7000};    merge_sort(arr, 11);    for(int i = 0; i < 11; ++i)    {        printf("%d ", arr[i]);    }    printf("\n");    return 0;}

 

C語言:歸併排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.