算法:插入排序(Insertion Sort)
2013-11-30 14:25
267 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataStuctureStudy.Sorts { /// <summary> /// 将数组分为两部分:已排序部分和未排序部分,对数组执行一次遍历,将遍历中的 /// 当前元素插入到已排序的部分。 /// 初始状态已排序部分只包括一个元素。 /// </summary> class InsertionSort<T> where T : IComparable<T> { private static void Swap(T[] items, int left, int right) { if (left != right) { var temp = items[left]; items[left] = items[right]; items[right] = temp; } } public static void Sort(T[] items) { for ( var sortedRangeEndIndex = 1; sortedRangeEndIndex < items.Length; sortedRangeEndIndex++) { if (items[sortedRangeEndIndex].CompareTo(items[sortedRangeEndIndex - 1]) < 0) { int insertIndex = FindInsertionIndex(items, items[sortedRangeEndIndex]); Insert(items, sortedRangeEndIndex, insertIndex); } } } private static int FindInsertionIndex(T[] items, T valueToInsert) { for (var i = 0; i < items.Length; i++) { if (items[i].CompareTo(valueToInsert) > 0) { return i; } } throw new InvalidOperationException(); } private static void Insert(T[] items, int indexInsertingFrom, int indexInsertingAt) { var temp = items[indexInsertingFrom]; for (var i = indexInsertingFrom; i > indexInsertingAt; i--) { items[i] = items[i - 1]; } items[indexInsertingAt] = temp; } } }
相关文章推荐
- 【算法】插入排序 insertion_sort
- Python 数据结构与算法——插入排序(insertion sort)
- 【算法】插入排序 insertion_sort
- 算法总结JS版(三)—— 插入排序(Insertion Sort)
- 【算法导论学习-001】插入排序(InsertionSort)
- 【DS】排序算法之插入排序(Insertion Sort)
- 算法-插入排序(Insertion Sort)
- 静态链表插入排序(List Insertion Sort)算法
- 插入排序(insertion sort)算法实现
- [算法练习]Insertion Sort 插入排序
- 算法:冒泡排序(Bubble Sort)、插入排序(Insertion Sort)和选择排序(Selection Sort)总结
- 算法学习记录-排序——插入排序(Insertion Sort)
- 【算法】插入排序(Insertion Sort)
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- 经典算法(8)- 插入排序(Insertion Sort) 及三个基本排序算法的比较
- 算法从排序开始——插入排序(Insertion Sort)C语言及Java实现
- leetcode——Insertion Sort List 对链表进行插入排序(AC)
- AOJ-ALDS1_1_A Insertion Sort【插入排序】
- LeetCode Insertion Sort List(单链表插入排序)
- 插入排序(InsertionSort)