c_cpp 递归C插入排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 递归C插入排序相关的知识,希望对你有一定的参考价值。

#include<stdio.h>
#define ARR_SIZE 6

void print_r(int *arr, size_t n);
void insertion_sort(int *arr, size_t n, size_t i);

int main(){
    int nums[ARR_SIZE] = {2,8,9,0,0,2};
    print_r(nums, ARR_SIZE);

    printf("Sorting...\n");
    insertion_sort(nums, ARR_SIZE, 0);
    print_r(nums, ARR_SIZE);


    return 0;
}

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

/*
 * This insertion sort will be done in place as opposed to the PHP
 * implementation.
 */
void insertion_sort(int *arr, size_t n, size_t i){
    int el,j;

    if(i == n-1){
        // Nothing to do since we're looking at the last element.
    }
    else{
        insertion_sort(arr, n, i+1);
        el = arr[i];

        // All elements to the right of index i are assumed to be sorted.
        // Now we just have to figure out where el fits in the sorted array
        for(j = i+1; j<n; j++){
            if(el > arr[j]){
                // el is bigger, swap so el moves to the right in the array.
                arr[j-1] = arr[j];
                arr[j] = el;
            }
        }
    }
}

以上是关于c_cpp 递归C插入排序的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 冒泡排序 - 递归

c_cpp 合并两个排序列表,递归和迭代

c_cpp 归并排序的非递归实现,慢于标准库

c_cpp 二叉搜索树的相关操作(创建,插入节点,前,中,后序递归和非递归遍历二叉树)

c_cpp 插入在C ++中排序

c_cpp 插入排序演示在c