Rust, Software Development

Insertion Sort Recursion and Iteration in Rust

This post is about the sorting algorithm called Insertion Sort using recursion and iteration in Rust. It is simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

Sort Using Recursion

Our codes have 2 functions. The first function only runs a recursive function.

The second function is the actual Insertion Sort function that uses recursion. It will call itself a number of times until the index + 1 is equals to or grater than the array length.

Below is an example of codes that use our bootstrap function.

The codes output the following.

Sort Using Iteration

For this example, we have a function that accepts a mutable reference to an array of i32’s with any length and returns nothing. This is the only function of the Insertion Sort using iteration. Notice that it only relies on a loop and does not call itself a number of times until an condition is met.

A sample usage would be:

This is the output of the Insertion Sort using iteration. Obviously, the output is the same using recursion.

Other Algorithms in Rust

For more algorithms in Rust, please go to Algorithms In Codes page.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like