1. 程式人生 > 其它 >歸併排序c語言版

歸併排序c語言版

技術標籤:筆記

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

void print(int *source, int length) {
    for (int i = 0; i < length; i++) {
        printf("%d ", source[i]);
    }
    printf("\n");
}

/* 要生成和返回隨機數的函式 */
void getRandom(int *target, const int
length) { /* 設定種子 */ srand((unsigned) time(NULL)); for (int i = 0; i < length; ++i) { target[i] = rand(); } } void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; } void copyArr(int *source, int *target, int start, int length) { // int length = sizeof(source) / sizeof(int);
// 不在在這裡計算陣列的長度,這裡的source是指標的長度 // 將陣列以引數的形式傳遞進來 for (int i = start; i < length; i++) { target[i - start] = source[i]; } } void sortArr(int *source, int n) { if (n < 2) { return; } if (n == 2) { if (source[0] > source[1]) { int tmp = source[0]
; source[0] = source[1]; source[1] = tmp; } } else { // 1. 拆分成兩個陣列 int leftHalfLength = n / 2; int rightHalfLength = n - leftHalfLength; int leftHalf[leftHalfLength]; int rightHalf[rightHalfLength]; copyArr(source, leftHalf, 0, leftHalfLength); copyArr(source, rightHalf, leftHalfLength, n); // 2. 遞迴呼叫sort sortArr(leftHalf, leftHalfLength); sortArr(rightHalf, rightHalfLength); // 3. 合併兩個有序陣列 int leftIndex = 0, rightIndex = 0, index = 0; while (leftIndex < leftHalfLength || rightIndex < rightHalfLength) { if (leftIndex >= leftHalfLength) { while (rightIndex < rightHalfLength) { source[index++] = rightHalf[rightIndex++]; } } if (rightIndex >= rightHalfLength) { while (leftIndex < leftHalfLength) { source[index++] = leftHalf[leftIndex++]; } } source[index++] = leftHalf[leftIndex] < rightHalf[rightIndex] ? leftHalf[leftIndex++] : rightHalf[rightIndex++]; } } } int main() { int length = 15; printf("input a number:"); scanf("%d",&length); if(length<1){ return 1; } int arr[length]; getRandom(arr, length); print(arr, length); sortArr(arr, length); print(arr, length); char a[20]; scanf("%s",&a); return 0; }