How to use C# to write an insertion sort algorithm
Insertion sort is a simple and intuitive sorting algorithm that is often used in actual development. It works by constructing an ordered sequence. For unsorted data, it scans from back to front in the sorted sequence, finds the corresponding position and inserts it.
Below we will introduce in detail how to use C# to write the insertion sort algorithm and provide specific code examples.
First, we need to define an array for sorting. In this example, we use an integer array for sorting, and the number of array elements is set to n.
int[] arr = new int[n];
Next, we can write the corresponding insertion sort algorithm.
public static void InsertionSort(int[] arr) { int n = arr.Length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } }
In this code, we use two loops to implement insertion sort. The outer loop starts from the second element until the last element, indicating the element currently to be inserted. The inner loop starts from the element currently to be inserted and continuously compares it with the sorted part to find the insertion position.
When the inner loop ends, we put the element currently to be inserted into the correct position and proceed to the next round of loop.
Finally, we can sort by calling the InsertionSort method.
int[] arr = { 9, 5, 1, 4, 3, 6, 8, 2, 7 }; InsertionSort(arr); Console.WriteLine("排序后的数组:"); foreach (int num in arr) { Console.Write(num + " "); }
In this example, we first create an array containing 9 integers and pass it as a parameter to the InsertionSort method. Then, we print the sorted array through a foreach loop.
Run the program and the output is as follows:
排序后的数组: 1 2 3 4 5 6 7 8 9
You can see that the insertion sort algorithm has successfully sorted the array.
To summarize, insertion sort is a simple but effective sorting algorithm. By continuously building an ordered sequence and inserting unsorted elements into the sorted sequence one by one, an ordered result can be quickly obtained. In actual development, we can modify the algorithm as needed to adapt to different types of data sorting. Through the above code examples, I believe you have mastered how to use C# to write the insertion sort algorithm. Hope this article is helpful to you!
The above is the detailed content of How to write insertion sort algorithm using C#. For more information, please follow other related articles on the PHP Chinese website!