插入排序算法 ,递归实现_C程序实现递归插入排序
插入排序算法 ,遞歸實(shí)現(xiàn)
The only difference between Insertion sort and Recursive Insertion Sort is that in the Recursive method, we start from placing the last element in its correct position in the sorted array instead of starting from the first.
插入排序和遞歸插入排序之間的唯一區(qū)別是,在遞歸方法中,我們從將最后一個(gè)元素放置在已排序數(shù)組中的正確位置開始,而不是從第一個(gè)元素開始。
Here, I will only be showing the C implementation of the sort as I have explained the basic theory in my previous article.
在這里,我將僅按照我在上一篇文章中解釋的基本理論來說明該類的C實(shí)現(xiàn)。
Recursive Insertion Sort Implementation:
遞歸插入排序?qū)崿F(xiàn):
#include <stdio.h>void rec_insertion(int arr[], int n) {// When the elements are all overif (n <= 1)return;// sorting n-1 elementsrec_insertion(arr, n - 1);int last = arr[n - 1];int j = n - 2;while (j >= 0 && last < arr[j]) {arr[j + 1] = arr[j];j--;}arr[j + 1] = last;printf("\nAfter performing Insertion sort:\n");for (int i = 0; i < n; i++)printf("%d ", arr[i]); }int main() {int arr[] = { 10, 14, 3, 8, 5, 12 };int n = sizeof(arr) / sizeof(arr[0]);rec_insertion(arr, n);return 0; }Output:
輸出:
After performing Insertion sort: 10 14 After performing Insertion sort: 3 10 14 After performing Insertion sort: 3 8 10 14 After performing Insertion sort: 3 5 8 10 14 After performing Insertion sort: 3 5 8 10 12 14This output shows the array after each ith iteration. Feel free to ask your doubts.
此輸出顯示每次第 i 次迭代后的數(shù)組。 隨時(shí)提出您的疑問。
翻譯自: https://www.includehelp.com/c-programs/implement-recursive-insertion-sort.aspx
插入排序算法 ,遞歸實(shí)現(xiàn)
總結(jié)
以上是生活随笔為你收集整理的插入排序算法 ,递归实现_C程序实现递归插入排序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转载] Python中定义函数,循环语
- 下一篇: java scanner_Java Sc