Last active
October 16, 2021 07:51
-
-
Save aannenko/f94d0f79a908acb0f556b9073b0a1b22 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Introduction to Algorithms, Third Edition - 2009 | |
using System; | |
using System.Collections.Generic; | |
Console.WriteLine(string.Join(' ', new[] { 5, 2, 4, 6, 1, 3 }.InsertionSortOptimized())); | |
Console.WriteLine(string.Join(' ', new[] { 31, 41, 59, 26, 41, 58 }.InsertionSortOptimized())); | |
static class ArrayExtensions | |
{ | |
public static T[] InsertionSort<T>(this T[] array, IComparer<T> comparer = null) | |
{ | |
if (array == null || array.Length < 2) | |
return array; | |
comparer ??= Comparer<T>.Default; | |
for (int j = 1; j < array.Length; j++) | |
{ | |
var key = array[j]; | |
var i = j - 1; | |
while (i > -1 && comparer.Compare(array[i], key) > 0) | |
{ | |
array[i + 1] = array[i]; | |
i--; | |
} | |
array[i + 1] = key; | |
} | |
return array; | |
} | |
public static T[] InsertionSortOptimized<T>(this T[] array, IComparer<T> comparer = null) | |
{ | |
if (array == null || array.Length < 2) | |
return array; | |
comparer ??= Comparer<T>.Default; | |
for (int j = 1; j < array.Length; j++) | |
{ | |
var key = array[j]; | |
int i = j - 1; | |
for (; i > -1 && comparer.Compare(array[i], key) > 0; i--); | |
if (++i == j) | |
continue; | |
Array.Copy(array, i, array, i + 1, j - i); | |
array[i] = key; | |
} | |
return array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment