白季飞龙的个人主页

排序算法

插入排序

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

void print_arr(int *arr, int len);

void insertion_sort(int *arr, int len);

int main() {

    int arr[] = {2, 5, 3, 3, 1};
    int len = sizeof(arr) / sizeof(arr[0]);

    printf("Before sorted:\n");
    print_arr(arr, len);

    insertion_sort(arr, len);

    printf("After sorted:\n");
    print_arr(arr, len);

    return EXIT_SUCCESS;
}

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

void insertion_sort(int *arr, int len) {
    for (int i = 1; i < len; ++i) {
        int target = arr[i];
        int j = i - 1;

        while (target < arr[j] && j >= 0) {
            arr[j + 1] = arr[j];
            --j;
        }
        arr[j + 1] = target;
    }
}

漫漫路,莫论逍遥;潜心修,只为悟道