├── .gitattributes ├── .gitignore ├── Images ├── HeapList.PNG └── HeapTree.PNG ├── PracticeTasks ├── PracticeTaskUnitTest │ ├── PracticeTaskUnitTest.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── UTBigNumber.cs │ ├── UTMatrixOperation.cs │ └── UTRPNTree.cs ├── PracticeTasks.sln └── PracticeTasks │ ├── App.config │ ├── BigNumberAddition.cs │ ├── MainProgram.cs │ ├── MatrixOperation.cs │ ├── PracticeTasks.csproj │ ├── Properties │ └── AssemblyInfo.cs │ ├── RPNTree.cs │ └── ReversePolishNotationEvaluation.cs ├── README.md ├── SortingAlgorithms ├── SortingAlgorithms.sln ├── SortingAlgorithms │ ├── BinarySort.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── SortingAlgorithms.csproj └── UnitTestSortingAlgorithms │ ├── Properties │ └── AssemblyInfo.cs │ ├── UnitTestBinarySort.cs │ └── UnitTestSortingAlgorithms.csproj ├── Yu.DataStructure.NonGeneric ├── Yu.DataStructure.NonGeneric.sln ├── Yu.DataStructure.NonGeneric │ ├── BinarySort.cs │ ├── DijkstrasAlgorithm.cs │ ├── Graph.cs │ ├── Heap.cs │ ├── LinearSort.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ └── Yu.DataStructure.NonGeneric.csproj └── Yu.DataStructure.NonGenericTest │ ├── AdvancedSortTest.cs │ ├── DijkstrasAlgorithmTest.cs │ ├── GraphTest.cs │ ├── HeapTest.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── SortTest.cs │ └── Yu.DataStructure.NonGenericTest.csproj ├── YuGeneric ├── UnitTestLList │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── UnitTestBinarySearchTree.cs │ ├── UnitTestBinaryTree.cs │ ├── UnitTestHeapList.cs │ ├── UnitTestLList.cs │ ├── UnitTestQueue.cs │ ├── UnitTestStack.cs │ ├── UnitTestTestClass.cs │ └── Yu.DataStructure.GenericTest.csproj ├── Yu.DataStructure.Generic.sln ├── YuGeneric │ ├── BinarySearchTree.cs │ ├── BinaryTree.cs │ ├── HeapList.cs │ ├── LList.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Queue.cs │ ├── Stack.cs │ ├── TestClass.cs │ └── Yu.DataStructure.Generic.csproj └── `Notes │ └── BinaryTreePostOrderTraversalWithStack.txt └── notes ├── BalancedBinaryTreeSearchComplexity.md ├── BubbleSort.md ├── GraphAndDijkstrasAlgorithm.md ├── Heap.md ├── HeapSort.md ├── InsertionSort.md ├── MergeSort.md ├── QuickSort.md ├── RadixSort.md ├── SelectionSort.md └── SortingAlgorithms └── QuickSort.md /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # Build results 11 | [Dd]ebug/ 12 | [Dd]ebugPublic/ 13 | [Rr]elease/ 14 | [Rr]eleases/ 15 | x64/ 16 | x86/ 17 | build/ 18 | bld/ 19 | [Bb]in/ 20 | [Oo]bj/ 21 | 22 | # Roslyn cache directories 23 | *.ide/ 24 | 25 | # MSTest test Results 26 | [Tt]est[Rr]esult*/ 27 | [Bb]uild[Ll]og.* 28 | 29 | #NUNIT 30 | *.VisualState.xml 31 | TestResult.xml 32 | 33 | # Build Results of an ATL Project 34 | [Dd]ebugPS/ 35 | [Rr]eleasePS/ 36 | dlldata.c 37 | 38 | *_i.c 39 | *_p.c 40 | *_i.h 41 | *.ilk 42 | *.meta 43 | *.obj 44 | *.pch 45 | *.pdb 46 | *.pgc 47 | *.pgd 48 | *.rsp 49 | *.sbr 50 | *.tlb 51 | *.tli 52 | *.tlh 53 | *.tmp 54 | *.tmp_proj 55 | *.log 56 | *.vspscc 57 | *.vssscc 58 | .builds 59 | *.pidb 60 | *.svclog 61 | *.scc 62 | 63 | # Chutzpah Test files 64 | _Chutzpah* 65 | 66 | # Visual C++ cache files 67 | ipch/ 68 | *.aps 69 | *.ncb 70 | *.opensdf 71 | *.sdf 72 | *.cachefile 73 | 74 | # Visual Studio profiler 75 | *.psess 76 | *.vsp 77 | *.vspx 78 | 79 | # TFS 2012 Local Workspace 80 | $tf/ 81 | 82 | # Guidance Automation Toolkit 83 | *.gpState 84 | 85 | # ReSharper is a .NET coding add-in 86 | _ReSharper*/ 87 | *.[Rr]e[Ss]harper 88 | *.DotSettings.user 89 | 90 | # JustCode is a .NET coding addin-in 91 | .JustCode 92 | 93 | # TeamCity is a build add-in 94 | _TeamCity* 95 | 96 | # DotCover is a Code Coverage Tool 97 | *.dotCover 98 | 99 | # NCrunch 100 | _NCrunch_* 101 | .*crunch*.local.xml 102 | 103 | # MightyMoose 104 | *.mm.* 105 | AutoTest.Net/ 106 | 107 | # Web workbench (sass) 108 | .sass-cache/ 109 | 110 | # Installshield output folder 111 | [Ee]xpress/ 112 | 113 | # DocProject is a documentation generator add-in 114 | DocProject/buildhelp/ 115 | DocProject/Help/*.HxT 116 | DocProject/Help/*.HxC 117 | DocProject/Help/*.hhc 118 | DocProject/Help/*.hhk 119 | DocProject/Help/*.hhp 120 | DocProject/Help/Html2 121 | DocProject/Help/html 122 | 123 | # Click-Once directory 124 | publish/ 125 | 126 | # Publish Web Output 127 | *.[Pp]ublish.xml 128 | *.azurePubxml 129 | # TODO: Comment the next line if you want to checkin your web deploy settings 130 | # but database connection strings (with potential passwords) will be unencrypted 131 | *.pubxml 132 | *.publishproj 133 | 134 | # NuGet Packages 135 | *.nupkg 136 | # The packages folder can be ignored because of Package Restore 137 | **/packages/* 138 | # except build/, which is used as an MSBuild target. 139 | !**/packages/build/ 140 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 141 | #!**/packages/repositories.config 142 | 143 | # Windows Azure Build Output 144 | csx/ 145 | *.build.csdef 146 | 147 | # Windows Store app package directory 148 | AppPackages/ 149 | 150 | # Others 151 | sql/ 152 | *.Cache 153 | ClientBin/ 154 | [Ss]tyle[Cc]op.* 155 | ~$* 156 | *~ 157 | *.dbmdl 158 | *.dbproj.schemaview 159 | *.pfx 160 | *.publishsettings 161 | node_modules/ 162 | 163 | # RIA/Silverlight projects 164 | Generated_Code/ 165 | 166 | # Backup & report files from converting an old project file 167 | # to a newer Visual Studio version. Backup files are not needed, 168 | # because we have git ;-) 169 | _UpgradeReport_Files/ 170 | Backup*/ 171 | UpgradeLog*.XML 172 | UpgradeLog*.htm 173 | 174 | # SQL Server files 175 | *.mdf 176 | *.ldf 177 | 178 | # Business Intelligence projects 179 | *.rdl.data 180 | *.bim.layout 181 | *.bim_*.settings 182 | 183 | # Microsoft Fakes 184 | FakesAssemblies/ 185 | 186 | # ========================= 187 | # Operating System Files 188 | # ========================= 189 | 190 | # OSX 191 | # ========================= 192 | 193 | .DS_Store 194 | .AppleDouble 195 | .LSOverride 196 | 197 | # Thumbnails 198 | ._* 199 | 200 | # Files that might appear on external disk 201 | .Spotlight-V100 202 | .Trashes 203 | 204 | # Directories potentially created on remote AFP share 205 | .AppleDB 206 | .AppleDesktop 207 | Network Trash Folder 208 | Temporary Items 209 | .apdisk 210 | 211 | # Windows 212 | # ========================= 213 | 214 | # Windows image file caches 215 | Thumbs.db 216 | ehthumbs.db 217 | 218 | # Folder config file 219 | Desktop.ini 220 | 221 | # Recycle Bin used on file shares 222 | $RECYCLE.BIN/ 223 | 224 | # Windows Installer files 225 | *.cab 226 | *.msi 227 | *.msm 228 | *.msp 229 | 230 | # Windows shortcuts 231 | *.lnk 232 | -------------------------------------------------------------------------------- /Images/HeapList.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bysz71/DataStructureAndAlgorithmsInCSharp/486c2c79537bd673a317ccd6b33f1eb3035d7ea5/Images/HeapList.PNG -------------------------------------------------------------------------------- /Images/HeapTree.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bysz71/DataStructureAndAlgorithmsInCSharp/486c2c79537bd673a317ccd6b33f1eb3035d7ea5/Images/HeapTree.PNG -------------------------------------------------------------------------------- /PracticeTasks/PracticeTaskUnitTest/PracticeTaskUnitTest.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {C99088B4-53E3-410F-A814-67C1085B2A76} 7 | Library 8 | Properties 9 | PracticeTaskUnitTest 10 | PracticeTaskUnitTest 11 | v4.5 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | ..\..\YuGeneric\YuGeneric\bin\Debug\YuGeneric.dll 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | {930772b6-0b06-450d-a2d6-6a808cecf7cd} 64 | PracticeTasks 65 | 66 | 67 | 68 | 69 | 70 | 71 | False 72 | 73 | 74 | False 75 | 76 | 77 | False 78 | 79 | 80 | False 81 | 82 | 83 | 84 | 85 | 86 | 87 | 94 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTaskUnitTest/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("PracticeTaskUnitTest")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("PracticeTaskUnitTest")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("3f21c91e-d5cf-4444-8859-82e46e0d21b5")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTaskUnitTest/UTBigNumber.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using YuGeneric; 4 | using PracticeTasks; 5 | 6 | namespace PracticeTaskUnitTest 7 | { 8 | [TestClass] 9 | public class UTBigNumber 10 | { 11 | [TestMethod] 12 | public void BigNumberConstructor(){ 13 | var op1 = new BigNumber(); 14 | var op2 = new BigNumber("21389101312"); 15 | } 16 | 17 | [TestMethod] 18 | public void BigNumberFirst() 19 | { 20 | var op1 = new BigNumber("12345"); 21 | Console.WriteLine(op1.First.Value); 22 | } 23 | 24 | [TestMethod] 25 | public void BigNumberWrite() 26 | { 27 | var op1 = new BigNumber("123123213"); 28 | op1.Write(); 29 | } 30 | 31 | [TestMethod] 32 | public void BigNumberPlusOverloading() 33 | { 34 | var op1 = new BigNumber("2139583949"); 35 | var op2 = new BigNumber("0192309890213"); 36 | var op3 = new BigNumber("0"); 37 | var op4 = new BigNumber(); 38 | 39 | var sum1 = op1 + op2; 40 | var sum2 = op2 + op3; 41 | var sum3 = op3 + op4; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTaskUnitTest/UTMatrixOperation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using YuGeneric; 4 | using PracticeTasks; 5 | 6 | namespace PracticeTaskUnitTest 7 | { 8 | [TestClass] 9 | public class UTMatrixOperation 10 | { 11 | [TestMethod] 12 | public void MatrixNodeConstructor() 13 | { 14 | var node = new MatrixNode(10, 10, 10); 15 | } 16 | 17 | [TestMethod] 18 | public void MatrixNodeProperty() 19 | { 20 | var node = new MatrixNode(10, 11, 12); 21 | Assert.AreEqual(node.Value, 10); 22 | Assert.AreEqual(node.Row, 11); 23 | Assert.AreEqual(node.Col, 12); 24 | } 25 | 26 | [TestMethod] 27 | public void MatrixConstructor() 28 | { 29 | var matrix1 = new Matrix(6); 30 | var matrix2 = new Matrix("matrix1.txt"); 31 | } 32 | 33 | [TestMethod] 34 | public void MatrixSize() 35 | { 36 | var matrix1 = new Matrix(6); 37 | var matrix2 = new Matrix("matrix1.txt"); 38 | 39 | Assert.AreEqual(matrix1.Size, 6); 40 | Assert.AreEqual(matrix2.Size, 4); 41 | } 42 | 43 | [TestMethod] 44 | public void MatrixAddNode() 45 | { 46 | var matrix = new Matrix(4); 47 | matrix.AddNode(4, 4, 4); 48 | } 49 | 50 | [TestMethod] 51 | public void MatrixWriteMatrix() 52 | { 53 | var matrix = new Matrix("matrix1.txt"); 54 | matrix.WriteMatrix("Matrix 1: "); 55 | } 56 | 57 | [TestMethod] 58 | public void MatrixAddMatrix() 59 | { 60 | var matrix1 = new Matrix("matrix1.txt"); 61 | var matrix2 = new Matrix("matrix2.txt"); 62 | 63 | var matrix3 = Matrix.AddMatrix(matrix1, matrix2); 64 | matrix1.WriteMatrix("Matrix 1: "); 65 | matrix2.WriteMatrix("Matrix 2: "); 66 | matrix3.WriteMatrix("Matrix Result: "); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTaskUnitTest/UTRPNTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using PracticeTasks; 4 | 5 | namespace PracticeTaskUnitTest 6 | { 7 | [TestClass] 8 | public class UTRPNTree 9 | { 10 | [TestMethod] 11 | public void RPNTreeRPNToTree() 12 | { 13 | var root = RPNTree.RPNToTree("34+78+*5+"); 14 | Console.Write(root.Value); 15 | } 16 | 17 | [TestMethod] 18 | public void RPNTreeWriteInFix() 19 | { 20 | var root = RPNTree.RPNToTree("34+78+*5+"); 21 | RPNTree.WriteInFix(root); 22 | } 23 | 24 | [TestMethod] 25 | public void RPNTreeWritePostFix() 26 | { 27 | var root = RPNTree.RPNToTree("34+78+*5+"); 28 | RPNTree.WritePostFix(root); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PracticeTasks", "PracticeTasks\PracticeTasks.csproj", "{930772B6-0B06-450D-A2D6-6A808CECF7CD}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PracticeTaskUnitTest", "PracticeTaskUnitTest\PracticeTaskUnitTest.csproj", "{C99088B4-53E3-410F-A814-67C1085B2A76}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {930772B6-0B06-450D-A2D6-6A808CECF7CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {930772B6-0B06-450D-A2D6-6A808CECF7CD}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {930772B6-0B06-450D-A2D6-6A808CECF7CD}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {930772B6-0B06-450D-A2D6-6A808CECF7CD}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {C99088B4-53E3-410F-A814-67C1085B2A76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {C99088B4-53E3-410F-A814-67C1085B2A76}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {C99088B4-53E3-410F-A814-67C1085B2A76}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {C99088B4-53E3-410F-A814-67C1085B2A76}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks/BigNumberAddition.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using YuGeneric; 7 | 8 | namespace PracticeTasks 9 | { 10 | public class BigNumberAddition 11 | { 12 | public static void Run() 13 | { 14 | var op1 = new BigNumber("000000000000"); 15 | var op2 = new BigNumber("000000000001"); 16 | var sum = op1 + op2; 17 | 18 | op1 = new BigNumber("99"); 19 | op2 = new BigNumber("1"); 20 | sum = op1 + op2; 21 | 22 | op1 = new BigNumber("999999999999"); 23 | op2 = new BigNumber("999999999999"); 24 | sum = op1 + op2; 25 | } 26 | } 27 | 28 | public class BigNumber 29 | { 30 | private LList _list; 31 | 32 | public BigNumber() 33 | { 34 | _list = new LList(); 35 | } 36 | 37 | public BigNumber(string bigNumString){ 38 | _list = new LList(); 39 | StringToList(bigNumString); 40 | } 41 | 42 | public LListNode First 43 | { 44 | get 45 | { 46 | return _list.First; 47 | } 48 | } 49 | 50 | private void AddLast(char sum) 51 | { 52 | _list.AddLast(sum); 53 | } 54 | 55 | /// 56 | /// Save a string into the list in a reverse way 57 | /// It is for iterating convinience 58 | /// 59 | /// 60 | private void StringToList(string bigNumString){ 61 | char[] chars = bigNumString.ToCharArray(); 62 | for (int i = 0; i < chars.Length; i++) 63 | { 64 | _list.AddFirst(chars[i]); 65 | } 66 | } 67 | 68 | /// 69 | /// check if the list is empty 70 | /// 71 | /// 72 | private bool IsEmpty() 73 | { 74 | if (_list.IsEmpty()) 75 | return true; 76 | else 77 | return false; 78 | } 79 | 80 | /// 81 | /// Reversely write the list to the screen 82 | /// 83 | public void Write() 84 | { 85 | var current = _list.First; 86 | string temp = ""; 87 | while (current != null) 88 | { 89 | temp = current.Value + temp; 90 | current = current.Next; 91 | } 92 | Console.WriteLine(temp); 93 | } 94 | 95 | /// 96 | /// operator + overloaded 97 | /// addtion of 2 bignumber can use + now 98 | /// write the oprands and result to the screen 99 | /// return a sum bignumber 100 | /// 101 | /// LHS oprand 102 | /// RHS oprand 103 | /// sum bignumber 104 | public static BigNumber operator +(BigNumber op1, BigNumber op2) 105 | { 106 | if (op1.IsEmpty() && op2.IsEmpty()) 107 | { 108 | return null; 109 | } 110 | else if (op1.IsEmpty()) 111 | { 112 | return op2; 113 | } 114 | else if (op2.IsEmpty()) 115 | { 116 | return op1; 117 | } 118 | else 119 | { 120 | int sum ; 121 | int carry = 0; 122 | var current1 = op1.First; 123 | var current2 = op2.First; 124 | var result = new BigNumber(); 125 | 126 | //if any of those 2 still have digits, looping 127 | while (current1 != null || current2 != null) 128 | { 129 | //reset sum to 0 every turn of loop 130 | //take the carry value from last turn 131 | sum = 0; 132 | 133 | //if available add current value to the sum 134 | //Char.GetNumericValue returns int of char's literal value 135 | //thus it does not need to go through ASCII conversion 136 | if (current1 != null) 137 | { 138 | sum += (int)Char.GetNumericValue(current1.Value); 139 | current1 = current1.Next; 140 | } 141 | 142 | if (current2 != null) 143 | { 144 | sum += (int)Char.GetNumericValue(current2.Value); 145 | current2 = current2.Next; 146 | } 147 | 148 | //add carry to sum, last turn carry now expired 149 | sum += carry; 150 | 151 | //new carry and new sum 152 | carry = sum / 10; 153 | sum = sum % 10; 154 | 155 | //add sum to the list 156 | //sum must add 48 according to ASCII table to make a char's literal is this sum 157 | //AddLast because need to make sure lower digits are at LHS of the list 158 | result.AddLast((char)(sum+48)); 159 | } 160 | 161 | //if carry is not zero, and a new node in the list represent 1 162 | if (carry == 1) 163 | result.AddLast((char)49); 164 | 165 | //print result to screen 166 | op1.Write(); 167 | Console.WriteLine("+"); 168 | op2.Write(); 169 | Console.WriteLine("="); 170 | result.Write(); 171 | 172 | return result; 173 | } 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks/MainProgram.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using YuGeneric; 7 | 8 | namespace PracticeTasks 9 | { 10 | class MainProgram 11 | { 12 | static void Main(string[] args) 13 | { 14 | BigNumberAddition.Run(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks/MatrixOperation.cs: -------------------------------------------------------------------------------- 1 | //Program reads in 2 sparse matrices from txt files 2 | //Store them as linked list 3 | //Perform Addition of 2 matrices 4 | //Store result in a linked list 5 | //Display all 3 matrices 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | using YuGeneric; 12 | using System.IO; 13 | 14 | namespace PracticeTasks 15 | { 16 | public class MatrixOperation 17 | { 18 | public static void MatrixOperationGo() 19 | { 20 | var matrix1 = new Matrix("matrix1.txt"); 21 | var matrix2 = new Matrix("matrix2.txt"); 22 | 23 | var matrix3 = Matrix.AddMatrix(matrix1, matrix2); 24 | matrix1.WriteMatrix("Matrix 1: "); 25 | matrix2.WriteMatrix("Matrix 2: "); 26 | matrix3.WriteMatrix("Matrix Result: "); 27 | } 28 | } 29 | 30 | public class MatrixNode 31 | { 32 | int _value; 33 | int _row; 34 | int _col; 35 | 36 | /// 37 | /// MatrixNode constructor 38 | /// 39 | /// Matrix node value 40 | /// Matrix node x coordinate 41 | /// Matrix node y coordinate 42 | public MatrixNode(int value, int row, int col) 43 | { 44 | _value = value; 45 | _row = row; 46 | _col = col; 47 | } 48 | 49 | public int Value 50 | { 51 | get 52 | { 53 | return _value; 54 | } 55 | } 56 | 57 | public int Row 58 | { 59 | get 60 | { 61 | return _row; 62 | } 63 | } 64 | 65 | public int Col 66 | { 67 | get 68 | { 69 | return _col; 70 | } 71 | } 72 | 73 | /// 74 | /// Overriden ToString() from the System.Object 75 | /// Return a string with only the value of the matrix node 76 | /// But not its coordinate 77 | /// 78 | /// 79 | public override string ToString() 80 | { 81 | return _value.ToString(); 82 | } 83 | } 84 | 85 | public class Matrix 86 | { 87 | LList _list; 88 | int _matrixSize; 89 | 90 | /// 91 | /// Matrix Constructor 92 | /// Takes a size parameter and establish a new empty LList 93 | /// 94 | /// 95 | public Matrix(int size) 96 | { 97 | _matrixSize = size; 98 | _list = new LList(); 99 | } 100 | 101 | /// 102 | /// Matrix Constructor 103 | /// Takes a fileName parameter 104 | /// Read and assign size from the file 105 | /// Add nodes into new established LList base on the file content 106 | /// 107 | /// 108 | public Matrix(string fileName) 109 | { 110 | StreamReader file = new StreamReader(fileName); 111 | //read in first line to get size of matrix 112 | string[] temp = file.ReadLine().Split(' '); 113 | _matrixSize = Convert.ToInt32(temp[0]); 114 | 115 | _list = new LList(); 116 | //interate through each line 117 | //add a matrixNode if the value is not zero 118 | int row = 0; 119 | int value = 0; 120 | while (file.Peek() > 0) 121 | { 122 | var temp2 = file.ReadLine().Split(' '); 123 | for (int i = 0; i < _matrixSize; i++) 124 | { 125 | value = Convert.ToInt32(temp2[i]); 126 | if (value != 0) 127 | { 128 | AddNode(value, row, i); 129 | } 130 | } 131 | row++; 132 | } 133 | } 134 | 135 | public int Size 136 | { 137 | get 138 | { 139 | return _matrixSize; 140 | } 141 | } 142 | 143 | public LList List 144 | { 145 | get 146 | { 147 | return _list; 148 | } 149 | } 150 | 151 | /// 152 | /// Overriden ToString() method 153 | /// Assign all none-zero values of the matrix into one string 154 | /// use space to split each other 155 | /// 156 | /// 157 | public override string ToString() 158 | { 159 | var current = _list.First; 160 | string result = ""; 161 | while (current != null) 162 | { 163 | result += current.Value.ToString(); 164 | if (current.Next != null) 165 | result += " "; 166 | current = current.Next; 167 | } 168 | return result; 169 | } 170 | 171 | /// 172 | /// Add a new node to the matrix list 173 | /// 174 | /// 175 | /// 176 | /// 177 | public void AddNode(int value, int row, int col) 178 | { 179 | _list.AddLast(new MatrixNode(value, row, col)); 180 | } 181 | 182 | /// 183 | /// Print whole matrix by some defined format 184 | /// 185 | /// 186 | public void WriteMatrix(string header) 187 | { 188 | string firstLine = ""; 189 | firstLine += header; 190 | firstLine += this.ToString(); 191 | Console.WriteLine(firstLine); 192 | 193 | var current = _list.First; 194 | for (int i = 0; i < Size; i++) 195 | { 196 | for (int j = 0; j < Size; j++) 197 | { 198 | if (current.Value.Row == i && current.Value.Col == j) 199 | { 200 | Console.Write(current.Value.Value); 201 | current = current.Next; 202 | } 203 | else 204 | { 205 | Console.Write(0); 206 | } 207 | 208 | if (j == 3) 209 | { 210 | Console.Write("\n"); 211 | } 212 | else 213 | { 214 | Console.Write(" "); 215 | } 216 | } 217 | } 218 | 219 | } 220 | 221 | /// 222 | /// A static method, used to add 2 matrices 223 | /// It returns a new matrix which represent the addition result of those 2 matrices 224 | /// 225 | /// 226 | /// 227 | /// 228 | public static Matrix AddMatrix(Matrix matrix1, Matrix matrix2) 229 | { 230 | //return null if matrix sizes do not match 231 | if (matrix1.Size != matrix2.Size) 232 | { 233 | Console.WriteLine("Cannot perfrom addition on 2 matrices with difference sizes"); 234 | return null; 235 | } 236 | 237 | //iterate through size*size, once coordinate appears in any of operands 238 | //and the sum is not zero, add a node in the new matrix with value of this 239 | //sum and coordinate of this coordinate 240 | var matrix = new Matrix(matrix1.Size); 241 | var current1 = matrix1.List.First; 242 | var current2 = matrix2.List.First; 243 | int sum = 0; 244 | for (int i = 0; i < matrix.Size; i++) 245 | { 246 | for (int j = 0; j < matrix.Size; j++) 247 | { 248 | sum = 0; 249 | if (current1.Value.Row == i && current1.Value.Col == j) 250 | { 251 | sum += current1.Value.Value; 252 | current1 = current1.Next; 253 | } 254 | if (current2.Value.Row == i && current2.Value.Col == j) 255 | { 256 | sum += current2.Value.Value; 257 | current2 = current2.Next; 258 | } 259 | if (sum != 0) 260 | { 261 | matrix.List.AddLast(new MatrixNode(sum, i, j)); 262 | } 263 | } 264 | } 265 | 266 | return matrix; 267 | } 268 | } 269 | } 270 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks/PracticeTasks.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {930772B6-0B06-450D-A2D6-6A808CECF7CD} 8 | Exe 9 | Properties 10 | PracticeTasks 11 | PracticeTasks 12 | v4.5 13 | 512 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | ..\..\YuGeneric\YuGeneric\bin\Debug\YuGeneric.dll 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 65 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("PracticeTasks")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("PracticeTasks")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("193e641a-22a9-486f-af27-380cf35e5802")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks/RPNTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | using YuGeneric; 6 | 7 | namespace PracticeTasks 8 | { 9 | public class RPNTree 10 | { 11 | private static char[] optrs = { '+', '-', '*', '/' }; 12 | 13 | public static RPNTreeNode RPNToTree(string expression) 14 | { 15 | RPNTreeNode t1, t2; 16 | var s = new Stack(); 17 | char[] exps = expression.ToCharArray(); 18 | for (int i = 0; i < exps.Length; i++) 19 | { 20 | if (Char.IsNumber(exps[i])) 21 | { 22 | s.Push(new RPNTreeNode(exps[i],null,null)); 23 | continue; 24 | } 25 | if(optrs.Contains(exps[i])){ 26 | t1 = s.Top.Value; 27 | s.Pop(); 28 | t2 = s.Top.Value; 29 | s.Pop(); 30 | s.Push(new RPNTreeNode(exps[i], t2, t1)); 31 | } 32 | } 33 | return s.Top.Value; 34 | } 35 | 36 | public static void WriteInFix(RPNTreeNode root) 37 | { 38 | if (root.Left != null) 39 | { 40 | Console.Write("("); 41 | WriteInFix(root.Left); 42 | } 43 | Console.Write(root.Value); 44 | if (root.Right != null) 45 | { 46 | WriteInFix(root.Right); 47 | Console.Write(")"); 48 | } 49 | } 50 | 51 | public static void WritePostFix(RPNTreeNode root) 52 | { 53 | if(root.Left!=null) 54 | WritePostFix(root.Left); 55 | if(root.Right!=null) 56 | WritePostFix(root.Right); 57 | Console.Write(root.Value); 58 | } 59 | 60 | 61 | } 62 | public class RPNTreeNode 63 | { 64 | public char Value; 65 | public RPNTreeNode Left; 66 | public RPNTreeNode Right; 67 | 68 | public RPNTreeNode(char value , RPNTreeNode left , RPNTreeNode right) 69 | { 70 | Value = value; 71 | Left = left; 72 | Right = right; 73 | } 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /PracticeTasks/PracticeTasks/ReversePolishNotationEvaluation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using YuGeneric; 7 | 8 | namespace PracticeTasks 9 | { 10 | public class ReversePolishNotationEvaluation 11 | { 12 | public static void Go() 13 | { 14 | string expr = "27 3 4 6 * + / 8 +"; 15 | int result = RPNEvaluator.Evaluate(expr); 16 | Console.WriteLine(result); 17 | } 18 | } 19 | 20 | public class RPNEvaluator 21 | { 22 | public static int Evaluate(string expr) 23 | { 24 | YuGeneric.Stack stack = new YuGeneric.Stack(); 25 | 26 | var operatorSet = new HashSet(); 27 | operatorSet.Add("+"); 28 | operatorSet.Add("-"); 29 | operatorSet.Add("*"); 30 | operatorSet.Add("/"); 31 | 32 | string[] items = expr.Split(' '); 33 | 34 | int op1, op2, result; 35 | int n; 36 | for (int i = 0; i < items.Length; i++) 37 | { 38 | if (int.TryParse(items[i], out n)) 39 | { 40 | stack.Push(Int32.Parse(items[i])); 41 | } 42 | 43 | if (operatorSet.Contains(items[i])) 44 | { 45 | if (stack.IsEmpty()) 46 | { 47 | Console.WriteLine("Not enough oprand."); 48 | System.Environment.Exit(1); 49 | } 50 | op2 = stack.Top.Value; 51 | stack.Pop(); 52 | if (stack.IsEmpty()) 53 | { 54 | Console.WriteLine("Not enough oprand."); 55 | System.Environment.Exit(1); 56 | } 57 | op1 = stack.Top.Value; 58 | stack.Pop(); 59 | result = calc(op1, op2, items[i]); 60 | stack.Push(result); 61 | } 62 | } 63 | result = stack.Top.Value; 64 | stack.Pop(); 65 | if (!stack.IsEmpty()) 66 | { 67 | Console.WriteLine("Two many oprand."); 68 | System.Environment.Exit(1); 69 | } 70 | return result; 71 | } 72 | 73 | public static int calc(int op1, int op2, string oprt) 74 | { 75 | if (oprt == "+") 76 | return op1 + op2; 77 | if (oprt == "-") 78 | return op1 - op2; 79 | if (oprt == "*") 80 | return op1 * op2; 81 | if (oprt == "/") 82 | { 83 | try 84 | { 85 | return op1 / op2; 86 | } 87 | catch(DivideByZeroException) 88 | { 89 | Console.WriteLine("Division of {0} by zero.", op1); 90 | System.Environment.Exit(1); 91 | } 92 | } 93 | throw new System.InvalidOperationException("Operator not iligible"); 94 | //System.Environment.Exit(1); 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Common Data Structure And Algorithms Implementation Using C# 2 | ============================================================ 3 | 4 | Preface 5 | -------- 6 | Using C# to implement data structure and algorithms seems redundant, because C# provides everything developers need to let them focus on applcation layer. Although C# is not the best choice to study and explain data structure and algorithms, it is perfectly capable of implementing them in a desired depth. This choice is due to personal interests in C# language and .NET framework. 7 | 8 | Introduction 9 | ------------ 10 | This project implements some common data structures and algorithms in C#. As I mentioned before, although C# isn't the usual 11 | choice, it is fully capable. I start this project to review data structures and algorithms and to practice C#. This is also a platform for people who is interested in algorithm learning to discuss and exchange ideas. 12 | 13 | I will try to give detailed explaination to every topic I list, and I will try to expand the list. 14 | 15 | Index (so far) 16 | ----------- 17 | ###Data Structures & Algorithms: 18 | * LinkedList 19 | * Stack 20 | * Queue 21 | * BinaryTree 22 | * BinarySearchTree 23 | * [Heap](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/Heap.md) 24 | * [Graph and Dijkstra's Algorithm](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/GraphAndDijkstrasAlgorithm.md) 25 | * Linear Sort 26 | + [Selection Sort](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/SelectionSort.md) 27 | + [Insertion Sort](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/InsertionSort.md) 28 | + [Bubble Sort](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/BubbleSort.md) 29 | * Binary Sort 30 | + [Merge Sort](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/MergeSort.md) 31 | + [Quicksort](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/QuickSort.md) 32 | + [Heap Sort](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/HeapSort.md) 33 | * Other Sort 34 | + [Radix Sort](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/RadixSort.md) 35 | 36 | ###Some practices 37 | * BigNumberAddition (LinkedList) 38 | * MatrixOperation (LinkedList) 39 | * RPNEvaluation (Stack) 40 | * RPNTree (BinaryTree) 41 | -------------------------------------------------------------------------------- /SortingAlgorithms/SortingAlgorithms.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SortingAlgorithms", "SortingAlgorithms\SortingAlgorithms.csproj", "{25DB1A0F-0CBC-4BF5-AA8D-78095B18B445}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTestSortingAlgorithms", "UnitTestSortingAlgorithms\UnitTestSortingAlgorithms.csproj", "{9941C986-203D-4B61-9D31-EDE1424A6BC5}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {25DB1A0F-0CBC-4BF5-AA8D-78095B18B445}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {25DB1A0F-0CBC-4BF5-AA8D-78095B18B445}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {25DB1A0F-0CBC-4BF5-AA8D-78095B18B445}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {25DB1A0F-0CBC-4BF5-AA8D-78095B18B445}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {9941C986-203D-4B61-9D31-EDE1424A6BC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {9941C986-203D-4B61-9D31-EDE1424A6BC5}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {9941C986-203D-4B61-9D31-EDE1424A6BC5}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {9941C986-203D-4B61-9D31-EDE1424A6BC5}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /SortingAlgorithms/SortingAlgorithms/BinarySort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace SortingAlgorithms 8 | { 9 | public class BinarySort 10 | { 11 | /// 12 | /// Quick sort using Lomuto partition schemme 13 | /// 14 | /// 15 | /// 16 | /// 17 | public static void QuickSort(int[] nums, int low, int high) 18 | { 19 | if (low < high) 20 | { 21 | int pivot = Partition(nums, low, high); 22 | QuickSort(nums, low, pivot - 1); 23 | QuickSort(nums, pivot + 1, high); 24 | } 25 | } 26 | 27 | //Lomuto partition scheme 28 | private static int Partition(int[] nums, int low, int high) 29 | { 30 | int pivot = nums[high]; 31 | int i = low; 32 | for (int j = low; j < high; j++) 33 | if (nums[j] <= pivot) 34 | Swap(ref nums[i++], ref nums[j]); 35 | Swap(ref nums[i], ref nums[high]); 36 | return i; 37 | } 38 | 39 | //swap the value of 2 ints 40 | private static void Swap(ref int left, ref int right) 41 | { 42 | int buff = left; 43 | left = right; 44 | right = buff; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /SortingAlgorithms/SortingAlgorithms/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SortingAlgorithms")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SortingAlgorithms")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("5e9cb0dd-5c24-4efc-af68-0b94e382dc12")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SortingAlgorithms/SortingAlgorithms/SortingAlgorithms.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {25DB1A0F-0CBC-4BF5-AA8D-78095B18B445} 8 | Library 9 | Properties 10 | SortingAlgorithms 11 | SortingAlgorithms 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 53 | -------------------------------------------------------------------------------- /SortingAlgorithms/UnitTestSortingAlgorithms/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("UnitTestSortingAlgorithms")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("UnitTestSortingAlgorithms")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("ac34a84c-dc34-438f-bec9-c737b8b0bb56")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SortingAlgorithms/UnitTestSortingAlgorithms/UnitTestBinarySort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using SortingAlgorithms; 4 | 5 | namespace UnitTestSortingAlgorithms 6 | { 7 | [TestClass] 8 | public class UnitTestBinarySort 9 | { 10 | [TestMethod] 11 | public void TestMethodQuickSort() 12 | { 13 | var nums = new int[] { 3, 9, 2, 5, 6, 4, 11, 7, 12 }; 14 | BinarySort.QuickSort(nums, 0, nums.Length - 1); 15 | CollectionAssert.AreEqual(new int[] { 2, 3, 4, 5, 6, 7, 9, 11, 12 }, nums); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /SortingAlgorithms/UnitTestSortingAlgorithms/UnitTestSortingAlgorithms.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {9941C986-203D-4B61-9D31-EDE1424A6BC5} 7 | Library 8 | Properties 9 | UnitTestSortingAlgorithms 10 | UnitTestSortingAlgorithms 11 | v4.5 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | {25db1a0f-0cbc-4bf5-aa8d-78095b18b445} 59 | SortingAlgorithms 60 | 61 | 62 | 63 | 64 | 65 | 66 | False 67 | 68 | 69 | False 70 | 71 | 72 | False 73 | 74 | 75 | False 76 | 77 | 78 | 79 | 80 | 81 | 82 | 89 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yu.DataStructure.NonGeneric", "Yu.DataStructure.NonGeneric\Yu.DataStructure.NonGeneric.csproj", "{65BA0CD9-44B9-4DD6-A252-EC0704EF0B0C}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yu.DataStructure.NonGenericTest", "Yu.DataStructure.NonGenericTest\Yu.DataStructure.NonGenericTest.csproj", "{8682B6FF-156A-4C49-B0E8-47480EA68097}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {65BA0CD9-44B9-4DD6-A252-EC0704EF0B0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {65BA0CD9-44B9-4DD6-A252-EC0704EF0B0C}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {65BA0CD9-44B9-4DD6-A252-EC0704EF0B0C}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {65BA0CD9-44B9-4DD6-A252-EC0704EF0B0C}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {8682B6FF-156A-4C49-B0E8-47480EA68097}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {8682B6FF-156A-4C49-B0E8-47480EA68097}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {8682B6FF-156A-4C49-B0E8-47480EA68097}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {8682B6FF-156A-4C49-B0E8-47480EA68097}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/BinarySort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.NonGeneric 8 | { 9 | public class BinarySort 10 | { 11 | /// 12 | /// Merge Sort Recursively 13 | /// Break array into smallest chunks 14 | /// And merge back 15 | /// 16 | /// 17 | /// 18 | /// 19 | /// 20 | public static void MergeSort(int[] data, int[] temp, int first, int last) 21 | { 22 | int mid = (first + last) / 2; 23 | if (first < last) 24 | { 25 | MergeSort(data, temp, first, mid); 26 | MergeSort(data, temp, mid + 1, last); 27 | Merge(data, temp, first, last); 28 | } 29 | } 30 | 31 | /// 32 | /// Merge 2 arrays 33 | /// by order of from smaller to larger 34 | /// A private method serves MergeSortRec() 35 | /// 36 | /// 37 | /// 38 | /// 39 | /// 40 | private static void Merge(int[] data, int[] temp, int first, int last) 41 | { 42 | int maxLow = (first + last) / 2; 43 | int low = first; 44 | int high = maxLow + 1; 45 | int i = first; 46 | 47 | while (low <= maxLow && high <= last) 48 | { 49 | if (data[low] < data[high]) 50 | temp[i++] = data[low++]; 51 | else 52 | temp[i++] = data[high++]; 53 | } 54 | 55 | while (low <= maxLow) 56 | temp[i++] = data[low++]; 57 | 58 | while (high <= last) 59 | temp[i++] = data[high++]; 60 | 61 | for (int j = first; j <= last; j++) 62 | data[j] = temp[j]; 63 | } 64 | 65 | /// 66 | /// Quicksort 67 | /// Time Complexity O(NlogN) 68 | /// Pick a value, place smaller value to left and bigger to right, place this value between them 69 | /// do left part the same way and right part the same way 70 | /// again and again recursively untill chunk smaller than 2 71 | /// 72 | /// 73 | /// 74 | /// 75 | public static void QuickSort(int[] data, int first, int last) 76 | { 77 | int pivot = data[first]; 78 | int inc = first + 1; 79 | int dec = last; 80 | 81 | while (inc < dec) 82 | { 83 | while (data[inc] < pivot && inc < last) 84 | inc++; 85 | while (data[dec] > pivot) 86 | dec--; 87 | if (inc < dec) Swap(data, inc, dec); 88 | } 89 | 90 | 91 | if (pivot > data[dec]) Swap(data, first, dec); 92 | 93 | if (dec - 1 > first) 94 | { 95 | QuickSort(data, first, dec - 1); 96 | } 97 | 98 | if (dec + 1 < last) 99 | { 100 | QuickSort(data, dec + 1, last); 101 | } 102 | } 103 | 104 | /// 105 | /// Swap values of 2 items in an array 106 | /// 107 | /// 108 | /// 109 | /// 110 | public static void Swap(int[] data, int left, int right) 111 | { 112 | int buff = data[left]; 113 | data[left] = data[right]; 114 | data[right] = buff; 115 | } 116 | 117 | public static void PrintArray(int[] data) 118 | { 119 | foreach (int i in data) 120 | { 121 | Console.Write(i + " "); 122 | } 123 | Console.Write("\n"); 124 | } 125 | 126 | /// 127 | /// RadixSort 128 | /// Time complexity O(KN) 129 | /// 130 | /// 131 | public static void RadixSort(int[] data) 132 | { 133 | int maxDigits = 3; 134 | int factor = 1; 135 | int n = 0; 136 | Queue[] Q = new Queue[10]; 137 | for (int i = 0; i < 10; i++ ) 138 | { 139 | Q[i] = new Queue(); 140 | } 141 | for (int digit = 1; digit <= maxDigits; digit++) 142 | { 143 | foreach (int entry in data) 144 | { 145 | Q[entry / factor % 10].Enqueue(entry); 146 | Console.WriteLine("Q[" + entry / factor % 10 + "] joined " + entry); 147 | } 148 | 149 | n = 0; 150 | foreach (Queue entry in Q) 151 | { 152 | while (entry.Count() != 0) 153 | { 154 | Console.WriteLine("n="+n); 155 | data[n++] = entry.Dequeue(); 156 | } 157 | } 158 | factor *= 10; 159 | } 160 | } 161 | 162 | /// 163 | /// use heap to sort 164 | /// Similar to merge and quick sort 165 | /// Time complexity O(NlogN) 166 | /// 167 | /// 168 | public static void HeapSort(int[] data) 169 | { 170 | var heap = new Heap(); 171 | foreach (int i in data) 172 | { 173 | heap.Insert(i); 174 | } 175 | 176 | for (int j = 0; heap.Count() > 0; j++) 177 | { 178 | data[j] = heap.DeleteRoot(); 179 | } 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/DijkstrasAlgorithm.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.NonGeneric 8 | { 9 | public class DijkstrasAlgorithm 10 | { 11 | public static void FindShortestPath(Graph graph, char start) 12 | { 13 | var d = new Dictionary(); 14 | var s = new Dictionary(); 15 | 16 | char current = start; 17 | d[start] = 0; 18 | s[start] = true; 19 | foreach (LinkedList entry in graph.List) 20 | { 21 | if (entry.First.Value.Key != start){ 22 | d[entry.First.Value.Key] = 1000000; 23 | s[entry.First.Value.Key] = false; 24 | } 25 | } 26 | 27 | char bufferChar; 28 | int bufferInt; 29 | while (s.ContainsValue(false)) 30 | { 31 | bufferChar = current; 32 | bufferInt = 10000000; 33 | foreach (Edge edge in graph.LList(current)) 34 | { 35 | if (edge.Key != current) 36 | { 37 | d[edge.Key] = Math.Min(d[edge.Key], d[current] + graph.GetEdge(current, edge.Key).Distance); 38 | } 39 | } 40 | 41 | foreach (KeyValuePair entry in s) 42 | { 43 | if (entry.Value == false) 44 | { 45 | if (d[entry.Key] < bufferInt) 46 | { 47 | bufferInt = d[entry.Key]; 48 | bufferChar = entry.Key; 49 | } 50 | } 51 | } 52 | current = bufferChar; 53 | s[current] = true; 54 | } 55 | 56 | foreach (KeyValuePair entry in d) 57 | { 58 | Console.Write("(" + entry.Key + "," + s[entry.Key] + "," + entry.Value + ") "); 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/Graph.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace Yu.DataStructure.NonGeneric 9 | { 10 | /// 11 | /// Graph type 12 | /// Compose by a List of EdgeList 13 | /// 14 | public class Graph 15 | { 16 | private List> _list; 17 | 18 | /// 19 | /// Default constructor 20 | /// 21 | public Graph() 22 | { 23 | _list = new List>(); 24 | } 25 | 26 | /// 27 | /// COnstructor based on a file 28 | /// 29 | /// 30 | public Graph(string fileName) 31 | { 32 | _list = new List>(); 33 | StreamReader file = new StreamReader(fileName); 34 | string buffer; 35 | string[] bufferArray; 36 | while((buffer = file.ReadLine())!=null){ 37 | if (String.Compare(buffer.Substring(0, 1),"#") == 0) 38 | { 39 | continue; 40 | } 41 | if (String.Compare(buffer.Substring(0, 4), "Node") == 0) 42 | { 43 | AddNode(buffer.Substring(5, 1)[0]); 44 | continue; 45 | } 46 | bufferArray = buffer.Split(' '); 47 | AddEdge(bufferArray[0][0], bufferArray[1][0], bufferArray[2][0]); 48 | } 49 | file.Close(); 50 | } 51 | 52 | /// 53 | /// Property returns _list 54 | /// 55 | public List> List 56 | { 57 | get 58 | { 59 | return _list; 60 | } 61 | } 62 | 63 | /// 64 | /// Return specific LinkedList of some key 65 | /// 66 | /// 67 | /// 68 | public LinkedList LList(char key) 69 | { 70 | return _list[_list.FindIndex(x => x.First.Value.Key == key)]; 71 | } 72 | 73 | /// 74 | /// Return an edge 75 | /// 76 | /// 77 | /// 78 | /// 79 | public Edge GetEdge(char from, char to) 80 | { 81 | foreach (Edge edge in LList(from)) 82 | { 83 | if (edge.Key == to) return edge; 84 | } 85 | return null; 86 | } 87 | 88 | /// 89 | /// Add a node. 90 | /// Add a new LinkedList with First item that key is key and distance is 0. 91 | /// 92 | /// 93 | public void AddNode(char key) 94 | { 95 | if (ContainsNode(key)) 96 | { 97 | Console.WriteLine("Error: Node {0} already existed. You cannot add duplicate node.", key); 98 | return; 99 | } 100 | var lList = new LinkedList(); 101 | lList.AddFirst(new Edge(key, 0)); 102 | _list.Add(lList); 103 | } 104 | 105 | /// 106 | /// Check if the graph have this node already 107 | /// 108 | /// 109 | /// 110 | public bool ContainsNode(char key) 111 | { 112 | foreach (LinkedList item in _list) 113 | { 114 | if (item.First.Value.Key == key) return true; 115 | } 116 | return false; 117 | } 118 | 119 | /// 120 | /// Check if the graph have such edge with same from and to 121 | /// 122 | /// 123 | /// 124 | /// 125 | public bool ContainsEdge(char from, char to) 126 | { 127 | foreach (Edge item in LList(from)) 128 | { 129 | if (item.Key == to) return true; 130 | } 131 | return false; 132 | } 133 | 134 | /// 135 | /// Add an edge 136 | /// 137 | /// 138 | /// 139 | /// 140 | public void AddEdge(char from, char to, int distance) 141 | { 142 | if (!ContainsNode(from) || !ContainsNode(to)) 143 | { 144 | Console.WriteLine("Error: Node not existed. AddEdge() must be based on existed node."); 145 | return; 146 | } 147 | 148 | if (ContainsEdge(from, to)) 149 | { 150 | Console.WriteLine("Error: Edge to {0} already existed in node {1}. You cannot add duplicate edge.", to, from); 151 | return; 152 | } 153 | 154 | LList(from).AddLast(new Edge(to, distance)); 155 | } 156 | 157 | /// 158 | /// Print whole graph 159 | /// 160 | public void Print() 161 | { 162 | Console.WriteLine("===Print Whole Graph Adjacent List==="); 163 | foreach (LinkedList item in _list) 164 | { 165 | foreach (Edge edge in item) 166 | { 167 | Console.Write("|" + edge.Key + "|" + edge.Distance + "|" + "->"); 168 | } 169 | Console.Write("Null\n"); 170 | } 171 | Console.WriteLine("===Print Finished==="); 172 | } 173 | 174 | /// 175 | /// Print specific LinkedList 176 | /// 177 | /// 178 | public void Print(char key) 179 | { 180 | Console.Write("Adjacent List of node " + key + ": "); 181 | foreach (Edge edge in LList(key)) 182 | { 183 | Console.Write("|" + edge.Key + "|" + edge.Distance + "|" + "->"); 184 | } 185 | Console.Write("Null\n"); 186 | } 187 | } 188 | 189 | public class Edge 190 | { 191 | public char Key; 192 | public int Distance; 193 | 194 | public Edge(char key, int distance) 195 | { 196 | Key = key; 197 | Distance = distance; 198 | } 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/Heap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.NonGeneric 8 | { 9 | public class Heap 10 | { 11 | private List _list; 12 | 13 | public Heap() 14 | { 15 | _list = new List(); 16 | } 17 | 18 | /// 19 | /// Insert an item to the heap 20 | /// swap if needed 21 | /// 22 | /// 23 | public void Insert(int item) 24 | { 25 | if (_list.Contains(item)) 26 | { 27 | Console.WriteLine("Error: Duplicate item"); 28 | return; 29 | } 30 | 31 | _list.Add(item); 32 | if (_list.Count() == 1) return; 33 | 34 | int motherIndex = 0; 35 | int childIndex = _list.Count() - 1; 36 | int buff = 0; 37 | 38 | while (true) 39 | { 40 | motherIndex = (childIndex - 1) / 2; 41 | if (_list[childIndex] > _list[motherIndex]) 42 | { 43 | buff = _list[childIndex]; 44 | _list[childIndex] = _list[motherIndex]; 45 | _list[motherIndex] = buff; 46 | childIndex = motherIndex; 47 | } 48 | else break; 49 | } 50 | } 51 | 52 | /// 53 | /// Delete largest value of the heap which is the root 54 | /// 55 | /// 56 | public int DeleteRoot() 57 | { 58 | int result; 59 | //empty heap case 60 | //if (_list.Count() == 0) 61 | //{ 62 | //Console.WriteLine("Error: Empty heap"); 63 | //return null; 64 | //} 65 | 66 | //one item cases 67 | if (_list.Count() == 1) 68 | { 69 | result = _list[0]; 70 | _list.RemoveAt(0); 71 | return result; 72 | } 73 | 74 | //other cases 75 | result = _list[0]; 76 | _list[0] = _list[_list.Count() - 1]; 77 | _list.RemoveAt(_list.Count() - 1); 78 | //swap 79 | int motherIndex = 0; 80 | int childIndex = 1; 81 | int buff = 0; 82 | while (true) 83 | { 84 | if (childIndex < _list.Count() - 1) 85 | { 86 | Console.WriteLine("both in range"); 87 | if (_list[motherIndex] < Math.Max(_list[childIndex], _list[childIndex + 1])) 88 | { 89 | 90 | buff = _list[motherIndex]; 91 | childIndex = MaxIndex(childIndex); 92 | _list[motherIndex] = _list[childIndex]; 93 | _list[childIndex] = buff; 94 | 95 | motherIndex = childIndex; 96 | childIndex = motherIndex * 2 + 1; 97 | } 98 | else break; 99 | } 100 | else if (childIndex == _list.Count() - 1) 101 | { 102 | if (_list[motherIndex] < _list[childIndex]) 103 | { 104 | buff = _list[motherIndex]; 105 | _list[motherIndex] = _list[childIndex]; 106 | _list[childIndex] = buff; 107 | } 108 | break; 109 | } 110 | else break; 111 | } 112 | return result; 113 | } 114 | 115 | /// 116 | /// returns the index of the biggest node in the 2 children node 117 | /// serves DeleteRoot() 118 | /// 119 | /// 120 | /// 121 | public int MaxIndex(int childIndex) 122 | { 123 | return _list.FindIndex(x => x == Math.Max(_list[childIndex], _list[childIndex + 1])); 124 | } 125 | 126 | /// 127 | /// Return how many items in the heap 128 | /// 129 | /// 130 | public int Count() 131 | { 132 | return _list.Count(); 133 | } 134 | 135 | /// 136 | /// print the whole heap 137 | /// 138 | public void Print() 139 | { 140 | foreach (int item in _list) 141 | Console.Write(item + " "); 142 | Console.Write("\n"); 143 | } 144 | 145 | public void Swap(int indexLeft, int indexRight) 146 | { 147 | int buff = _list[indexLeft]; 148 | _list[indexLeft] = _list[indexRight]; 149 | _list[indexRight] = buff; 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/LinearSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.NonGeneric 8 | { 9 | public class LinearSort 10 | { 11 | /// 12 | /// SelectionSorting 13 | /// Time complexity O(N^2) 14 | /// Usually for{for{}} causes O(N^2) time complexity 15 | /// Swap current item with currently smallest item 16 | /// 17 | /// 18 | public static void SelectionSort(int[] data) 19 | { 20 | int min = 0; 21 | int buffer = 0; 22 | for (int front = 0; front < data.Length; front++) 23 | { 24 | min = front; 25 | for (int i = front; i < data.Length; i++) 26 | { 27 | if (data[i] < data[min]) min = i; 28 | } 29 | buffer = data[min]; 30 | data[min] = data[front]; 31 | data[front] = buffer; 32 | } 33 | } 34 | 35 | /// 36 | /// Insertion Sorting 37 | /// Time complexity O(N^2) 38 | /// Shift array until reach the right order 39 | /// 40 | /// 41 | public static void InsertionSort(int[] data) 42 | { 43 | int buff; 44 | int shift; 45 | for (int i = 1; i < data.Length; i++) 46 | { 47 | buff = data[i]; 48 | for (shift = i; shift>0 && data[shift-1]>buff; shift--) 49 | { 50 | data[shift] = data[shift - 1]; 51 | } 52 | data[shift] = buff; 53 | } 54 | } 55 | 56 | /// 57 | /// Bubble Sort 58 | /// Time complexity O(N^2) 59 | /// Treat 2 neighbours as a window(bubble) 60 | /// swap if wrong order, and move on 61 | /// if nothing needs to swap in a whole turn, break 62 | /// 63 | /// 64 | public static void BubbleSort(int[] data) 65 | { 66 | int buff; 67 | bool swap = false; 68 | while (true) 69 | { 70 | swap = false; 71 | for (int i = 0; i < data.Length - 1; i++) 72 | { 73 | if (data[i] > data[i + 1]) 74 | { 75 | buff = data[i]; 76 | data[i] = data[i + 1]; 77 | data[i + 1] = buff; 78 | swap = true; 79 | } 80 | } 81 | if(swap == false) break; 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Yu.DataStructure.NonGeneric")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Yu.DataStructure.NonGeneric")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("b0fd9e63-deef-46b4-942a-a685e63cab7d")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {65BA0CD9-44B9-4DD6-A252-EC0704EF0B0C} 8 | Library 9 | Properties 10 | Yu.DataStructure.NonGeneric 11 | Yu.DataStructure.NonGeneric 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 57 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGenericTest/AdvancedSortTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.NonGeneric; 4 | 5 | namespace Yu.DataStructure.NonGenericTest 6 | { 7 | [TestClass] 8 | public class AdvancedSortTest 9 | { 10 | [TestMethod] 11 | public void TestMergeSort() 12 | { 13 | int[] data = new int[] { 10, 7, 2, 6, 2, 8, 9, 0, 15, 27, 11, 9 }; 14 | int[] temp = new int[12]; 15 | BinarySort.MergeSort(data, temp, 0, 11); 16 | foreach (int i in data) 17 | { 18 | Console.Write(i + " "); 19 | } 20 | } 21 | 22 | [TestMethod] 23 | public void TestSwap() 24 | { 25 | int[] data = new int[] { 10, 7, 2, 6, 2, 8, 9, 0, 15, 27, 11, 9 }; 26 | BinarySort.Swap(data, 0, 11); 27 | BinarySort.PrintArray(data); 28 | } 29 | 30 | [TestMethod] 31 | public void TestQuickSort() 32 | { 33 | int[] data = new int[] { 7, 3, 8, 2, 5, 6, 0, 1, 9, 4 }; 34 | BinarySort.QuickSort(data, 0, 9); 35 | foreach (int i in data) 36 | { 37 | Console.Write(i + " "); 38 | } 39 | } 40 | 41 | [TestMethod] 42 | public void TestRadixSort() 43 | { 44 | int[] data = new int[] { 5, 37, 1, 61, 11, 59, 48, 19 }; 45 | BinarySort.RadixSort(data); 46 | foreach (int i in data) 47 | { 48 | Console.Write(i + " "); 49 | } 50 | } 51 | 52 | [TestMethod] 53 | public void TestHeapSort() 54 | { 55 | int[] data = new int[] { 5, 37, 1, 61, 11, 59, 48, 19 }; 56 | BinarySort.HeapSort(data); 57 | foreach (int i in data) 58 | { 59 | Console.Write(i + " "); 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGenericTest/DijkstrasAlgorithmTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Yu.DataStructure.NonGeneric; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | namespace Yu.DataStructure.NonGenericTest 6 | { 7 | [TestClass] 8 | public class DijkstrasAlgorithmTest 9 | { 10 | [TestMethod] 11 | public void DAFindShortestPath() 12 | { 13 | var graph = new Graph("C:\\Users\\SCOTT\\Desktop\\159201\\Assignments\\6\\graph5.txt"); 14 | DijkstrasAlgorithm.FindShortestPath(graph, 'A'); 15 | Console.WriteLine(); 16 | var graph2 = new Graph("C:\\Users\\SCOTT\\Desktop\\159201\\Assignments\\6\\graph1.txt"); 17 | DijkstrasAlgorithm.FindShortestPath(graph2, 'A'); 18 | Console.WriteLine(); 19 | DijkstrasAlgorithm.FindShortestPath(graph, 'N'); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGenericTest/GraphTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.NonGeneric; 4 | 5 | namespace Yu.DataStructure.NonGenericTest 6 | { 7 | [TestClass] 8 | public class GraphTest 9 | { 10 | [TestMethod] 11 | public void EdgeConstructor() 12 | { 13 | var edge = new Edge('A', 10); 14 | } 15 | 16 | [TestMethod] 17 | public void GraphConstructor() 18 | { 19 | var graph = new Graph(); 20 | } 21 | 22 | [TestMethod] 23 | public void GraphAddNode() 24 | { 25 | var graph = new Graph(); 26 | graph.AddNode('A'); 27 | graph.AddNode('A'); 28 | graph.AddNode('B'); 29 | graph.Print(); 30 | } 31 | 32 | [TestMethod] 33 | public void GraphAddEdge() 34 | { 35 | var graph = new Graph(); 36 | graph.AddNode('A'); 37 | graph.AddNode('B'); 38 | graph.AddEdge('B', 'A', 10); 39 | graph.AddEdge('C', 'A', 10); 40 | graph.AddEdge('A', 'C', 10); 41 | graph.AddEdge('B', 'A', 10); 42 | graph.Print(); 43 | graph.Print('A'); 44 | } 45 | 46 | [TestMethod] 47 | public void GraphConstructorFromFile() 48 | { 49 | var graph = new Graph("C:\\Users\\SCOTT\\Desktop\\159201\\Assignments\\6\\graph5.txt"); 50 | graph.Print(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGenericTest/HeapTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.NonGeneric; 4 | using System.Collections.Generic; 5 | 6 | namespace Yu.DataStructure.NonGenericTest 7 | { 8 | [TestClass] 9 | public class UnitTestHeap 10 | { 11 | public void HeapInsertALot(Heap heap) 12 | { 13 | heap.Insert(10); 14 | heap.Insert(20); 15 | heap.Insert(5); 16 | heap.Insert(0); 17 | heap.Insert(28); 18 | heap.Insert(3); 19 | heap.Insert(15); 20 | } 21 | 22 | [TestMethod] 23 | public void HeapConstructor() 24 | { 25 | var heap = new Heap(); 26 | } 27 | 28 | [TestMethod] 29 | public void HeapListInsert() 30 | { 31 | var heap = new Heap(); 32 | heap.Insert(10); 33 | heap.Insert(20); 34 | heap.Insert(5); 35 | heap.Insert(5); 36 | } 37 | 38 | [TestMethod] 39 | public void HeapListPrint() 40 | { 41 | var heap = new Heap(); 42 | HeapInsertALot(heap); 43 | heap.Print(); 44 | } 45 | 46 | [TestMethod] 47 | public void HeapListDelete() 48 | { 49 | var heap = new Heap(); 50 | HeapInsertALot(heap); 51 | heap.Print(); 52 | heap.DeleteRoot(); 53 | heap.Print(); 54 | heap.DeleteRoot(); 55 | heap.Print(); 56 | } 57 | 58 | [TestMethod] 59 | public void HeapListMaxIndex() 60 | { 61 | var heap = new Heap(); 62 | HeapInsertALot(heap); 63 | Console.WriteLine(heap.MaxIndex(1)); 64 | Console.WriteLine(heap.MaxIndex(3)); 65 | Console.WriteLine(heap.MaxIndex(5)); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGenericTest/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Yu.DataStructure.NonGenericTest")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Yu.DataStructure.NonGenericTest")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("421f28e6-fe6d-4133-9773-14fa98c38bc9")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGenericTest/SortTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.NonGeneric; 4 | 5 | namespace Yu.DataStructure.NonGenericTest 6 | { 7 | [TestClass] 8 | public class SortTest 9 | { 10 | [TestMethod] 11 | public void TestSelectionSort() 12 | { 13 | int[] array = { 4, 7, 2, 3, 9, 8, 0, 1, 5, 6 }; 14 | LinearSort.SelectionSort(array); 15 | foreach (int i in array) 16 | { 17 | Console.Write(i + " "); 18 | } 19 | } 20 | 21 | [TestMethod] 22 | public void TestInsertionSort() 23 | { 24 | int[] array = { 4, 7, 2, 3, 9, 8, 0, 1, 5, 6 }; 25 | LinearSort.InsertionSort(array); 26 | foreach (int i in array) 27 | { 28 | Console.Write(i + " "); 29 | } 30 | } 31 | 32 | [TestMethod] 33 | public void TestBubbleSort() 34 | { 35 | int[] array = { 4, 7, 2, 3, 9, 8, 0, 1, 5, 6 }; 36 | LinearSort.BubbleSort(array); 37 | foreach (int i in array) 38 | { 39 | Console.Write(i + " "); 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGenericTest/Yu.DataStructure.NonGenericTest.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {8682B6FF-156A-4C49-B0E8-47480EA68097} 7 | Library 8 | Properties 9 | Yu.DataStructure.NonGenericTest 10 | Yu.DataStructure.NonGenericTest 11 | v4.5 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | {65ba0cd9-44b9-4dd6-a252-ec0704ef0b0c} 63 | Yu.DataStructure.NonGeneric 64 | 65 | 66 | 67 | 68 | 69 | 70 | False 71 | 72 | 73 | False 74 | 75 | 76 | False 77 | 78 | 79 | False 80 | 81 | 82 | 83 | 84 | 85 | 86 | 93 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Yu.DataStructure.GenericTest")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Yu.DataStructure.GenericTest")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("0f7fc44a-2f72-4afa-b090-2d79042c4d10")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/UnitTestBinarySearchTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.Generic; 4 | 5 | namespace Yu.DataStructure.GenericTest 6 | { 7 | [TestClass] 8 | public class UnitTestBinarySearchTree 9 | { 10 | public void MakeTree(TreeNodeInt root) 11 | { 12 | BinarySearchTree.Insert(root, 4); 13 | BinarySearchTree.Insert(root, 8); 14 | BinarySearchTree.Insert(root, 20); 15 | BinarySearchTree.Insert(root, 12); 16 | BinarySearchTree.Insert(root, 3); 17 | BinarySearchTree.Insert(root, 7); 18 | BinarySearchTree.Insert(root, 17); 19 | } 20 | 21 | [TestMethod] 22 | public void BSTInsert() 23 | { 24 | var root = new TreeNodeInt(10, null, null); 25 | BinarySearchTree.Insert(root, 8); 26 | BinarySearchTree.Insert(root, 20); 27 | BinarySearchTree.Insert(root, 10); 28 | } 29 | 30 | [TestMethod] 31 | public void BSTInOrder() 32 | { 33 | var root = new TreeNodeInt(10, null, null); 34 | MakeTree(root); 35 | BinarySearchTree.InOrderPrint(root); 36 | } 37 | 38 | [TestMethod] 39 | public void BSTSearch() 40 | { 41 | var root = new TreeNodeInt(10, null, null); 42 | MakeTree(root); 43 | Assert.AreEqual(BinarySearchTree.Search(root, 12).Value, 12); 44 | Assert.AreEqual(BinarySearchTree.Search(root, 10).Value, 10); 45 | Assert.ReferenceEquals(BinarySearchTree.Search(root, 222), null); 46 | } 47 | 48 | [TestMethod] 49 | public void BSTSearchRecursive() 50 | { 51 | var root = new TreeNodeInt(10, null, null); 52 | MakeTree(root); 53 | Assert.AreEqual(BinarySearchTree.SearchRecursive(root, 12).Value, 12); 54 | Assert.AreEqual(BinarySearchTree.SearchRecursive(root, 10).Value, 10); 55 | Assert.ReferenceEquals(BinarySearchTree.SearchRecursive(root, 222), null); 56 | } 57 | 58 | [TestMethod] 59 | public void BSTInsertNonRecursive() 60 | { 61 | var root = new TreeNodeInt(10, null, null); 62 | BinarySearchTree.InsertNonRecursive(root, 12); 63 | BinarySearchTree.InsertNonRecursive(root, 20); 64 | BinarySearchTree.InsertNonRecursive(root, 5); 65 | BinarySearchTree.InsertNonRecursive(root, 10); 66 | BinarySearchTree.InOrderPrint(root); 67 | } 68 | 69 | [TestMethod] 70 | public void BSTDelete() 71 | { 72 | var root = new TreeNodeInt(10, null, null); 73 | MakeTree(root); 74 | BinarySearchTree.Delete(ref root, 4); 75 | Assert.AreEqual(root.Left.Value, 7); 76 | BinarySearchTree.Insert(root, 40); 77 | BinarySearchTree.Insert(root, 30); 78 | BinarySearchTree.Insert(root, 50); 79 | BinarySearchTree.Insert(root, 35); 80 | BinarySearchTree.Delete(ref root, 40); 81 | Assert.AreEqual(BinarySearchTree.Search(root, 35).Left.Value, 30); 82 | Assert.AreEqual(BinarySearchTree.Search(root, 35).Right.Value, 50); 83 | Assert.ReferenceEquals(BinarySearchTree.Search(root,20).Right, BinarySearchTree.Search(root, 35)); 84 | } 85 | 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/UnitTestBinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.Generic; 4 | 5 | namespace Yu.DataStructure.GenericTest 6 | { 7 | [TestClass] 8 | public class UnitTestBinaryTree 9 | { 10 | [TestMethod] 11 | public void BinaryTreeNodeConstructor() 12 | { 13 | var node1 = new BinaryTreeNode(0, null, null); 14 | var node2 = new BinaryTreeNode("0", null, null); 15 | } 16 | 17 | [TestMethod] 18 | public void BinaryTreeNodeProperties() 19 | { 20 | var node1 = new BinaryTreeNode(1, null, null); 21 | var node2 = new BinaryTreeNode(2, null, null); 22 | var node0 = new BinaryTreeNode(0, node1, node2); 23 | Assert.AreEqual(node1.Value, 1); 24 | Assert.ReferenceEquals(node2.Left, null); 25 | Assert.ReferenceEquals(node0.Right, node2); 26 | 27 | var node3 = new BinaryTreeNode(3, null, null); 28 | var node4 = new BinaryTreeNode(4, null, null); 29 | node1.Left = node3; 30 | node2.Right = node4; 31 | node4.Value = 5; 32 | Assert.ReferenceEquals(node1.Left, node3); 33 | Assert.AreEqual(node2.Right, node4); 34 | Assert.AreEqual(node4.Value, 5); 35 | } 36 | 37 | [TestMethod] 38 | public void BinaryTreeConstructor() 39 | { 40 | var tree0 = new BinaryTree(0); 41 | var tree1 = new BinaryTree(new BinaryTreeNode(1, null, null)); 42 | } 43 | 44 | [TestMethod] 45 | public void BinaryTreeRoot() 46 | { 47 | var node1 = new BinaryTreeNode(1); 48 | var node2 = new BinaryTreeNode(2); 49 | var node0 = new BinaryTreeNode(0, node1, node2); 50 | var tree0 = new BinaryTree(node0); 51 | Assert.AreEqual(tree0.Root.Value, 0); 52 | } 53 | 54 | [TestMethod] 55 | public void BinaryTreeInOrder() 56 | { 57 | var node5 = new BinaryTreeNode(5); 58 | var node4 = new BinaryTreeNode(4); 59 | var node3 = new BinaryTreeNode(3); 60 | var node2 = new BinaryTreeNode(2, node5, null); 61 | var node1 = new BinaryTreeNode(1, node3, node4); 62 | var node0 = new BinaryTreeNode(0, node1, node2); 63 | 64 | BinaryTree.InOrder(node0); 65 | } 66 | 67 | [TestMethod] 68 | public void BinaryTreePreOrder() 69 | { 70 | var node5 = new BinaryTreeNode(5); 71 | var node4 = new BinaryTreeNode(4); 72 | var node3 = new BinaryTreeNode(3); 73 | var node2 = new BinaryTreeNode(2, node5, null); 74 | var node1 = new BinaryTreeNode(1, node3, node4); 75 | var node0 = new BinaryTreeNode(0, node1, node2); 76 | 77 | BinaryTree.PreOrder(node0); 78 | } 79 | 80 | [TestMethod] 81 | public void BinaryTreePostOrder() 82 | { 83 | var node5 = new BinaryTreeNode(5); 84 | var node4 = new BinaryTreeNode(4); 85 | var node3 = new BinaryTreeNode(3); 86 | var node2 = new BinaryTreeNode(2, node5, null); 87 | var node1 = new BinaryTreeNode(1, node3, node4); 88 | var node0 = new BinaryTreeNode(0, node1, node2); 89 | 90 | BinaryTree.PostOrder(node0); 91 | } 92 | 93 | [TestMethod] 94 | public void BinaryTreePreOrderWithStack() 95 | { 96 | var node5 = new BinaryTreeNode(5); 97 | var node4 = new BinaryTreeNode(4); 98 | var node3 = new BinaryTreeNode(3); 99 | var node2 = new BinaryTreeNode(2, node5, null); 100 | var node1 = new BinaryTreeNode(1, node3, node4); 101 | var node0 = new BinaryTreeNode(0, node1, node2); 102 | 103 | BinaryTree.PreOrderWithStack(node0); 104 | } 105 | 106 | [TestMethod] 107 | public void BinaryTreeInOrderWithStack() 108 | { 109 | var node5 = new BinaryTreeNode(5); 110 | var node4 = new BinaryTreeNode(4); 111 | var node3 = new BinaryTreeNode(3); 112 | var node2 = new BinaryTreeNode(2, node5, null); 113 | var node1 = new BinaryTreeNode(1, node3, node4); 114 | var node0 = new BinaryTreeNode(0, node1, node2); 115 | 116 | BinaryTree.InOrderWithStack(node0); 117 | } 118 | 119 | [TestMethod] 120 | public void BinaryTreePostOrderWithStack() 121 | { 122 | var node5 = new BinaryTreeNode(5); 123 | var node4 = new BinaryTreeNode(4); 124 | var node3 = new BinaryTreeNode(3); 125 | var node2 = new BinaryTreeNode(2, node5, null); 126 | var node1 = new BinaryTreeNode(1, node3, node4); 127 | var node0 = new BinaryTreeNode(0, node1, node2); 128 | 129 | BinaryTree.PostOrderWithStack(node0); 130 | } 131 | 132 | [TestMethod] 133 | public void BinaryTreeBreadthFirst() 134 | { 135 | var node5 = new BinaryTreeNode(5); 136 | var node4 = new BinaryTreeNode(4); 137 | var node3 = new BinaryTreeNode(3); 138 | var node2 = new BinaryTreeNode(2, node5, null); 139 | var node1 = new BinaryTreeNode(1, node3, node4); 140 | var node0 = new BinaryTreeNode(0, node1, node2); 141 | 142 | BinaryTree.BreadthFirstTraversal(node0); 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/UnitTestHeapList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.Generic; 4 | using System.Collections.Generic; 5 | 6 | namespace Yu.DataStructure.GenericTest 7 | { 8 | [TestClass] 9 | public class UnitTestHeapList 10 | { 11 | public void HeapListInsertALot(HeapList heap) 12 | { 13 | heap.Insert(10); 14 | heap.Insert(20); 15 | heap.Insert(5); 16 | heap.Insert(0); 17 | heap.Insert(28); 18 | heap.Insert(3); 19 | heap.Insert(15); 20 | } 21 | 22 | [TestMethod] 23 | public void HeapListConstructor() 24 | { 25 | var heap = new HeapList(); 26 | } 27 | 28 | [TestMethod] 29 | public void HeapListInsert() 30 | { 31 | var heap = new HeapList(); 32 | heap.Insert(10); 33 | heap.Insert(20); 34 | heap.Insert(5); 35 | heap.Insert(5); 36 | } 37 | 38 | [TestMethod] 39 | public void HeapListPrint() 40 | { 41 | var heap = new HeapList(); 42 | HeapListInsertALot(heap); 43 | heap.Print(); 44 | } 45 | 46 | [TestMethod] 47 | public void HeapListDelete() 48 | { 49 | var heap = new HeapList(); 50 | HeapListInsertALot(heap); 51 | heap.Print(); 52 | heap.DeleteRoot(); 53 | heap.Print(); 54 | heap.DeleteRoot(); 55 | heap.Print(); 56 | } 57 | 58 | [TestMethod] 59 | public void HeapListMaxIndex() 60 | { 61 | var heap = new HeapList(); 62 | HeapListInsertALot(heap); 63 | Console.WriteLine(heap.MaxIndex(1)); 64 | Console.WriteLine(heap.MaxIndex(3)); 65 | Console.WriteLine(heap.MaxIndex(5)); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/UnitTestLList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using System.Collections.Generic; 4 | using Yu.DataStructure.Generic; 5 | 6 | 7 | namespace Yu.DataStructure.GenericTest 8 | { 9 | [TestClass] 10 | public class UnitTestLList 11 | { 12 | [TestMethod] 13 | public void LListConstructor() 14 | { 15 | var lListString = new LList(); 16 | var lListInt = new LList(); 17 | var lListBool = new LList(); 18 | } 19 | 20 | [TestMethod] 21 | public void LListFirst() 22 | { 23 | var listVoid = new LList(); 24 | var listNotVoid = new LList(); 25 | listNotVoid.AddFirst(2000); 26 | 27 | Assert.ReferenceEquals(listVoid.First, null); 28 | Assert.AreEqual(listNotVoid.First.Value, 2000); 29 | } 30 | 31 | [TestMethod] 32 | public void LListLast() 33 | { 34 | var listVoid = new LList(); 35 | var listOne = new LList(); 36 | listOne.AddFirst(100); 37 | var listTwo = new LList(); 38 | listTwo.AddFirst(10); 39 | listTwo.AddFirst(20); 40 | 41 | Assert.ReferenceEquals(listVoid.Last, null); 42 | Assert.AreEqual(listOne.Last.Value, 100); 43 | Assert.AreEqual(listTwo.Last.Value, 10); 44 | } 45 | 46 | [TestMethod] 47 | public void LListAddFirst() 48 | { 49 | var list1 = new LList(); 50 | var list2 = new LList(); 51 | 52 | var node1 = new LListNode("node1"); 53 | var node2 = new LListNode("node2"); 54 | 55 | list1.AddFirst("111"); 56 | list1.AddFirst("222"); 57 | 58 | list2.AddFirst(node1); 59 | list2.AddFirst(node2); 60 | 61 | Console.WriteLine("List1: " + list1.ToString()); 62 | Console.WriteLine("List2: " + list2.ToString()); 63 | } 64 | 65 | [TestMethod] 66 | public void LListAddLast() 67 | { 68 | var list1 = new LList(); 69 | list1.AddLast(1); 70 | list1.AddLast(2); 71 | Console.WriteLine("list1: " + list1.ToString()); 72 | 73 | var list2 = new LList(); 74 | var node1 = new LListNode(1); 75 | var node2 = new LListNode(2); 76 | list2.AddLast(node1); 77 | list2.AddLast(node2); 78 | Console.WriteLine("list2: " + list2.ToString()); 79 | } 80 | 81 | [TestMethod] 82 | public void LListFind() 83 | { 84 | var list = new LList(); 85 | for (int i = 0; i < 10; i++) 86 | list.AddLast(i); 87 | var node = list.Find(3); 88 | Assert.AreEqual(node.Value, 3); 89 | 90 | var list2 = new LList(); 91 | list2.AddFirst("a"); 92 | list2.AddFirst("b"); 93 | list2.AddFirst("c"); 94 | var node2 = list2.Find("b"); 95 | Assert.AreEqual(node2.Value, "b"); 96 | 97 | var list3 = new LList(); 98 | var node3 = list3.Find(2); 99 | Assert.AreEqual(node3, null); 100 | } 101 | 102 | [TestMethod] 103 | public void LListFindLast() 104 | { 105 | var list = new LList(); 106 | list.AddLast(1); 107 | list.AddLast(1); 108 | list.AddLast(2); 109 | var node = list.FindLast(1); 110 | Assert.AreEqual(node.Next.Value, 2); 111 | 112 | var list2 = new LList(); 113 | list2.AddFirst(1); 114 | Assert.AreEqual(list2.FindLast(1).Value, 1); 115 | } 116 | 117 | [TestMethod] 118 | public void LListAddAfter() 119 | { 120 | var list = new LList(); 121 | list.AddLast(1); 122 | list.AddLast(2); 123 | list.AddLast(3); 124 | var node = list.Find(2); 125 | list.AddAfter(node, new LListNode(4)); 126 | list.AddAfter(list.Find(3), 5); 127 | Console.WriteLine(list.ToString() + "the _tail pointer is now: " + list.Last.Value); 128 | } 129 | 130 | [TestMethod] 131 | public void LListAddBefore() 132 | { 133 | var list = new LList(); 134 | list.AddLast(1); 135 | list.AddLast(2); 136 | list.AddLast(3); 137 | list.AddBefore(list.Find(2), new LListNode(4)); 138 | list.AddBefore(list.First, 5); 139 | Console.WriteLine(list.ToString() + "the _head pointer is now: " + list.First.Value); 140 | } 141 | 142 | [TestMethod] 143 | public void LListRemove() 144 | { 145 | var list = new LList(); 146 | Console.WriteLine("test void"); 147 | Console.WriteLine(list.RemoveFirst()); 148 | Console.WriteLine(list.RemoveLast()); 149 | Console.WriteLine(list.ToString()); 150 | 151 | list.AddFirst(10); 152 | Console.WriteLine("test 1 item list remove first"); 153 | Console.WriteLine(list.RemoveFirst()); 154 | Console.WriteLine(list.ToString()); 155 | 156 | list.AddFirst(10); 157 | Console.WriteLine("test 1 item list remove last"); 158 | Console.WriteLine(list.RemoveLast()); 159 | 160 | list.AddFirst(10); 161 | Console.WriteLine("test 1 item list remove value"); 162 | Console.WriteLine(list.Remove(10)); 163 | Console.WriteLine(list.ToString()); 164 | 165 | list.AddFirst(10); 166 | list.AddFirst(11); 167 | list.AddFirst(11); 168 | Console.WriteLine("test multi item list remove first item using remove(T) and remove first"); 169 | Console.WriteLine(list.Remove(11)); 170 | Console.WriteLine(list.ToString()); 171 | Console.WriteLine(list.RemoveFirst()); 172 | Console.WriteLine(list.ToString()); 173 | 174 | for (int i = 0; i < 10; i++) 175 | list.AddLast(i); 176 | 177 | list.Remove(0); 178 | list.Remove(10); 179 | Console.WriteLine(list.First.Value + ";" + list.Last.Value); 180 | } 181 | 182 | [TestMethod] 183 | public void LListCount() 184 | { 185 | var list = new LList(); 186 | list.AddLast(1); 187 | list.AddLast(2); 188 | Assert.AreEqual(list.Count(), 2); 189 | list.RemoveLast(); 190 | Assert.AreEqual(list.Count(), 1); 191 | list.RemoveLast(); 192 | Assert.AreEqual(list.Count(), 0); 193 | } 194 | 195 | [TestMethod] 196 | public void LListContains() 197 | { 198 | var list = new LList(); 199 | list.AddLast(10); 200 | if (list.Contains(10)) 201 | Console.WriteLine("list contains 10"); 202 | else 203 | Console.WriteLine("list does not contain 10"); 204 | 205 | var list2 = new LList(); 206 | list2.AddLast("asdf"); 207 | if(list2.Contains("asdf")) 208 | Console.WriteLine("list contains asdf"); 209 | else 210 | Console.WriteLine("list does not contain asdf"); 211 | if (list2.Contains("aaa")) 212 | Console.WriteLine("list contains aaa"); 213 | else 214 | Console.WriteLine("list does not contain aaa"); 215 | } 216 | 217 | [TestMethod] 218 | public void LListToString() 219 | { 220 | var list = new LList(); 221 | Console.WriteLine(list.ToString()); 222 | list.AddLast(10); 223 | Console.WriteLine(list.ToString()); 224 | for (int i = 0; i < 10; i++) 225 | { 226 | list.AddLast(i); 227 | } 228 | Console.WriteLine(list.ToString()); 229 | } 230 | 231 | [TestMethod] 232 | public void LListClear() 233 | { 234 | var list = new LList(); 235 | for (int i = 0; i < 10; i++) 236 | list.AddLast(i); 237 | list.Clear(); 238 | Assert.ReferenceEquals(list, null); 239 | Assert.AreEqual(list.Count(), 0); 240 | } 241 | 242 | [TestMethod] 243 | public void LListIsEmpty(){ 244 | var list = new LList(); 245 | Assert.AreEqual(list.IsEmpty(), true); 246 | Assert.ReferenceEquals(list.First, list.Last); 247 | list.AddFirst(10); 248 | Assert.AreEqual(list.IsEmpty(), false); 249 | Assert.ReferenceEquals(list.First, list.Last); 250 | list.Remove(10); 251 | Assert.ReferenceEquals(list.IsEmpty(), true); 252 | } 253 | 254 | [TestMethod] 255 | public void LListConcatenate() 256 | { 257 | var list1 = new LList(); 258 | for (int i = 0; i < 5; i++) 259 | { 260 | list1.AddLast(i); 261 | } 262 | var list2 = new LList(); 263 | for (int i = 10; i < 15; i++) 264 | { 265 | list2.AddLast(i); 266 | } 267 | 268 | LList.Concatenate(ref list1, ref list2); 269 | Console.WriteLine(list1.ToString()); 270 | Assert.AreEqual(list1.First.Value, 0); 271 | Assert.AreEqual(list1.Last.Value, 14); 272 | Assert.AreEqual(list2.First.Value, 10); 273 | Assert.AreEqual(list2.Last.Value, 14); 274 | 275 | //Console.WriteLine("---list1 empty state---"); 276 | var listEmpty = new LList(); 277 | LList.Concatenate(ref listEmpty, ref list1); 278 | Assert.AreEqual(listEmpty.First.Value, 0); 279 | Assert.AreEqual(listEmpty.Last.Value, 14); 280 | } 281 | 282 | [TestMethod] 283 | public void LListReverse1() 284 | { 285 | var list = new LList(); 286 | for (int i = 0; i < 5; i++) 287 | { 288 | list.AddLast(i); 289 | } 290 | LList.Reverse1(ref list); 291 | Assert.AreEqual(list.ToString(),"4,3,2,1,0"); 292 | 293 | var list1 = new LList(); 294 | LList.Reverse1(ref list1); 295 | Assert.AreEqual(list1.IsEmpty(), true); 296 | 297 | list1.AddLast(1); 298 | LList.Reverse1(ref list1); 299 | Assert.AreEqual(list1.ToString(), "1"); 300 | } 301 | 302 | [TestMethod] 303 | public void LListFindByPosition() 304 | { 305 | var list = new LList(); 306 | Assert.ReferenceEquals(list.FindByPosition(1), null); 307 | list.AddLast("zero"); 308 | list.AddLast("one"); 309 | list.AddLast("two"); 310 | Console.WriteLine(list.Count()); 311 | Assert.ReferenceEquals(list.FindByPosition(3), null); 312 | Assert.AreEqual(list.FindByPosition(0).Value, "zero"); 313 | Assert.AreEqual(list.FindByPosition(1).Value, "one"); 314 | Assert.AreEqual(list.FindByPosition(2).Value, "two"); 315 | } 316 | 317 | [TestMethod] 318 | public void LListReverse2() 319 | { 320 | var list = new LList(); 321 | for (int i = 0; i < 5; i++) 322 | { 323 | list.AddLast(i); 324 | } 325 | LList.Reverse2(list); 326 | Assert.AreEqual(list.ToString(), "4,3,2,1,0"); 327 | 328 | list.RemoveFirst(); 329 | LList.Reverse2(list); 330 | Assert.AreEqual(list.ToString(), "0,1,2,3"); 331 | 332 | var list2 = new LList(); 333 | list2.AddLast(1); 334 | Assert.AreEqual(list2.ToString(), "1"); 335 | } 336 | 337 | [TestMethod] 338 | public void LListReverse3() 339 | { 340 | var list = new LList(); 341 | list.AddLast(-1); 342 | LList.Reverse3(list); 343 | Assert.AreEqual(list.ToString(), "-1"); 344 | for (int i = 0; i < 10; i++) 345 | { 346 | list.AddLast(i); 347 | } 348 | LList.Reverse3(list); 349 | Assert.AreEqual(list.ToString(), "9,8,7,6,5,4,3,2,1,0,-1"); 350 | } 351 | 352 | [TestMethod] 353 | public void LListSplit() 354 | { 355 | var list = new LList(); 356 | LList result =LList.Split(list, 1); 357 | Assert.ReferenceEquals(result, null); 358 | 359 | for (int i = 0; i < 10; i++) 360 | { 361 | list.AddLast(i); 362 | } 363 | result = LList.Split(list, 100); 364 | Assert.ReferenceEquals(result, null); 365 | 366 | result = LList.Split(list, 5); 367 | Assert.AreEqual(list.ToString(), "0,1,2,3,4,5"); 368 | Assert.AreEqual(result.ToString(), "6,7,8,9"); 369 | } 370 | } 371 | } 372 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/UnitTestQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.Generic; 4 | 5 | namespace Yu.DataStructure.GenericTest 6 | { 7 | [TestClass] 8 | public class UnitTestQueue 9 | { 10 | [TestMethod] 11 | public void QueueNodeConstructor() 12 | { 13 | var node1 = new QueueNode(); 14 | var node2 = new QueueNode("aaa"); 15 | } 16 | 17 | [TestMethod] 18 | public void QueueNodeProperty() 19 | { 20 | var node = new QueueNode("bbb"); 21 | Assert.AreEqual(node.Value, "bbb"); 22 | Assert.ReferenceEquals(node.Next, null); 23 | 24 | var node2 = new QueueNode("ccc"); 25 | node2.Next = node; 26 | Assert.ReferenceEquals(node2.Next, node); 27 | } 28 | 29 | [TestMethod] 30 | public void QueueConstructor() 31 | { 32 | var qInt = new Queue(); 33 | var qString = new Queue(); 34 | } 35 | 36 | [TestMethod] 37 | public void QueueProperty() 38 | { 39 | var queue = new Queue(); 40 | Assert.ReferenceEquals(queue.Front, null); 41 | 42 | queue.Join(10); 43 | Assert.AreEqual(queue.Front.Value, 10); 44 | 45 | queue.Join(20); 46 | Assert.AreEqual(queue.Front.Value, 10); 47 | } 48 | 49 | [TestMethod] 50 | public void QueueCount() 51 | { 52 | var queue = new Queue(); 53 | Assert.AreEqual(queue.Count(), 0); 54 | 55 | queue.Join(0); 56 | Assert.AreEqual(queue.Count(), 1); 57 | 58 | for (int i = 0; i < 10; i++) 59 | { 60 | queue.Join(i); 61 | } 62 | Assert.AreEqual(queue.Count(), 11); 63 | } 64 | 65 | [TestMethod] 66 | public void QueueIsEmpty() 67 | { 68 | var queue = new Queue(); 69 | Assert.AreEqual(queue.IsEmpty(), true); 70 | queue.Join(10); 71 | Assert.AreEqual(queue.IsEmpty(), false); 72 | } 73 | 74 | [TestMethod] 75 | public void QueueJoin() 76 | { 77 | var queue = new Queue(); 78 | queue.Join(new QueueNode(10)); 79 | Assert.AreEqual(queue.Front.Value, 10); 80 | queue.Join(100); 81 | Assert.AreEqual(queue.Front.Value, 10); 82 | Assert.AreEqual(queue.Count(), 2); 83 | } 84 | 85 | [TestMethod] 86 | public void QueueLeave() 87 | { 88 | var queue = new Queue(); 89 | Assert.AreEqual(queue.Leave(), false); 90 | queue.Join(10); 91 | Assert.AreEqual(queue.Leave(), true); 92 | Assert.AreEqual(queue.IsEmpty(), true); 93 | queue.Join(20); 94 | queue.Join(30); 95 | Assert.AreEqual(queue.Leave(), true); 96 | Assert.AreEqual(queue.Count(), 1); 97 | Assert.AreEqual(queue.Front.Value, 30); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/UnitTestStack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.Generic; 4 | 5 | namespace Yu.DataStructure.GenericTest 6 | { 7 | [TestClass] 8 | public class UnitTestStack 9 | { 10 | [TestMethod] 11 | public void StackNodeConstructor() 12 | { 13 | var node1 = new StackNode(); 14 | var node2 = new StackNode(); 15 | 16 | var node3 = new StackNode(10); 17 | var node4 = new StackNode("aaa"); 18 | } 19 | 20 | [TestMethod] 21 | public void StackNodeProperty() 22 | { 23 | var node1 = new StackNode(10); 24 | Assert.AreEqual(node1.Value, 10); 25 | Assert.ReferenceEquals(node1.Next, null); 26 | } 27 | 28 | [TestMethod] 29 | public void StackConstructor() 30 | { 31 | var stack = new Stack(); 32 | var stack2 = new Stack(); 33 | } 34 | 35 | [TestMethod] 36 | public void StackTop() 37 | { 38 | var stack = new Stack(); 39 | stack.Push(10); 40 | stack.Push(20); 41 | Assert.AreEqual(stack.Top.Value, 20); 42 | stack.Top.Value = 30; 43 | Assert.AreEqual(stack.Top.Value, 30); 44 | } 45 | 46 | [TestMethod] 47 | public void StackPush() 48 | { 49 | var stack = new Stack(); 50 | stack.Push(10); 51 | stack.Push(10); 52 | var node = new StackNode(100); 53 | stack.Push(node); 54 | } 55 | 56 | [TestMethod] 57 | public void StackPop() 58 | { 59 | var stack = new Stack(); 60 | stack.Push(10); 61 | stack.Push(20); 62 | stack.Pop(); 63 | Assert.AreEqual(stack.Top.Value, 10); 64 | } 65 | 66 | [TestMethod] 67 | public void StackIsEmpty() 68 | { 69 | var stack = new Stack(); 70 | Assert.AreEqual(stack.IsEmpty(), true); 71 | stack.Push(10); 72 | Assert.AreEqual(stack.IsEmpty(), false); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/UnitTestTestClass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using Yu.DataStructure.Generic; 4 | 5 | namespace Yu 6 | { 7 | [TestClass] 8 | public class UnitTestTestClass 9 | { 10 | [TestMethod] 11 | public void TestReturnObj() 12 | { 13 | var x = TestClass.ReturnObj(); 14 | Console.Write(x.i + "--" + x.str); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /YuGeneric/UnitTestLList/Yu.DataStructure.GenericTest.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {D50024B3-6271-4430-8151-720B218AC2A2} 7 | Library 8 | Properties 9 | Yu 10 | Yu.DataStructure.GenericTest 11 | v4.5 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | {1a09f2e3-f75d-4a39-82d4-ce5897b3db5c} 65 | Yu.DataStructure.Generic 66 | 67 | 68 | 69 | 70 | 71 | 72 | False 73 | 74 | 75 | False 76 | 77 | 78 | False 79 | 80 | 81 | False 82 | 83 | 84 | 85 | 86 | 87 | 88 | 95 | -------------------------------------------------------------------------------- /YuGeneric/Yu.DataStructure.Generic.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yu.DataStructure.Generic", "YuGeneric\Yu.DataStructure.Generic.csproj", "{1A09F2E3-F75D-4A39-82D4-CE5897B3DB5C}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Yu.DataStructure.GenericTest", "UnitTestLList\Yu.DataStructure.GenericTest.csproj", "{D50024B3-6271-4430-8151-720B218AC2A2}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {1A09F2E3-F75D-4A39-82D4-CE5897B3DB5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {1A09F2E3-F75D-4A39-82D4-CE5897B3DB5C}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {1A09F2E3-F75D-4A39-82D4-CE5897B3DB5C}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {1A09F2E3-F75D-4A39-82D4-CE5897B3DB5C}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {D50024B3-6271-4430-8151-720B218AC2A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {D50024B3-6271-4430-8151-720B218AC2A2}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {D50024B3-6271-4430-8151-720B218AC2A2}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {D50024B3-6271-4430-8151-720B218AC2A2}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /YuGeneric/YuGeneric/BinarySearchTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.Generic 8 | { 9 | public class BinarySearchTree 10 | { 11 | /// 12 | /// Insert an int to a binary search tree 13 | /// It uses recursive to implement insertion 14 | /// It always add a new node to a leaf 15 | /// It never breaks a existed connection to break itself in 16 | /// 17 | /// the root node of the BST 18 | /// the int that will be inserted 19 | public static void Insert(TreeNodeInt root, int item) 20 | { 21 | if (item > root.Value) 22 | { 23 | if (root.Right == null) 24 | { 25 | root.Right = new TreeNodeInt(item, null, null); 26 | } 27 | else 28 | { 29 | Insert(root.Right, item); 30 | } 31 | } 32 | else if (item < root.Value) 33 | { 34 | if (root.Left == null) 35 | { 36 | root.Left = new TreeNodeInt(item, null, null); 37 | } 38 | else 39 | { 40 | Insert(root.Left, item); 41 | } 42 | } 43 | else 44 | { 45 | Console.WriteLine("Error: key is no unique"); 46 | return; 47 | } 48 | } 49 | 50 | /// 51 | /// Just print out the tree use InOrder traversal 52 | /// 53 | /// tree root node 54 | public static void InOrderPrint(TreeNodeInt root) 55 | { 56 | if (root == null) return; 57 | InOrderPrint(root.Left); 58 | Console.Write(root.Value + " "); 59 | InOrderPrint(root.Right); 60 | } 61 | 62 | /// 63 | /// Search a specific value in a BST 64 | /// Concept is kinda similar to Insert() 65 | /// But not using recursive way 66 | /// Which recursive can be used I think 67 | /// I'll write a recursive search 68 | /// 69 | /// tree root node 70 | /// search key value 71 | /// 72 | public static TreeNodeInt Search(TreeNodeInt root, int value) 73 | { 74 | var current = root; 75 | while (current != null) 76 | { 77 | if (current.Value == value) 78 | { 79 | Console.WriteLine("Found {0}", value); 80 | return current; 81 | } 82 | else if (value < current.Value) 83 | { 84 | current = current.Left; 85 | } 86 | else if (value > current.Value) 87 | { 88 | current = current.Right; 89 | } 90 | } 91 | Console.WriteLine("{0} is not found in the tree", value); 92 | return null; 93 | } 94 | 95 | /// 96 | /// Use recursive way to search a value 97 | /// So yes recursive way can be used in here 98 | /// Just same as insert 99 | /// so insert() can be rewritten in non-recursive way I think 100 | /// 101 | /// 102 | /// 103 | /// 104 | public static TreeNodeInt SearchRecursive(TreeNodeInt root, int value) 105 | { 106 | var current = root; 107 | if (value == current.Value) 108 | { 109 | Console.WriteLine(value + " Found"); 110 | }else if (value < current.Value) 111 | { 112 | if (current.Left == null) current = null; 113 | else current = SearchRecursive(current.Left, value); 114 | } 115 | else if (value > current.Value) 116 | { 117 | if (current.Right == null) current = null; 118 | else current = SearchRecursive(current.Right, value); 119 | } 120 | 121 | if (current == null) Console.WriteLine(value + " not found in the BST"); 122 | return current; 123 | } 124 | 125 | /// 126 | /// Insert a value using non-recursive way 127 | /// So yeah, using loop can acheive insertion 128 | /// 129 | /// 130 | /// 131 | public static void InsertNonRecursive(TreeNodeInt root, int value) 132 | { 133 | var current = root; 134 | while (current != null) 135 | { 136 | if (value == current.Value) 137 | { 138 | Console.WriteLine("Error: Un-Unique key not permitted."); 139 | return; 140 | } 141 | 142 | if (value < current.Value) 143 | { 144 | if (current.Left == null) 145 | { 146 | current.Left = new TreeNodeInt(value, null, null); 147 | Console.WriteLine(value + " added"); 148 | return; 149 | } 150 | else 151 | { 152 | current = current.Left; 153 | continue; 154 | } 155 | } 156 | 157 | if (value > current.Value) 158 | { 159 | if (current.Right == null) 160 | { 161 | current.Right = new TreeNodeInt(value, null, null); 162 | Console.WriteLine(value + " added"); 163 | return; 164 | } 165 | else 166 | { 167 | current = current.Right; 168 | continue; 169 | } 170 | } 171 | } 172 | } 173 | 174 | /// 175 | /// Delete a node when it is a leaf 176 | /// A method serves Delete() 177 | /// 178 | /// 179 | /// 180 | /// 181 | private static bool DeleteLeaf(ref TreeNodeInt root, int value) 182 | { 183 | var current = root; 184 | if (root.Value == value) 185 | { 186 | Console.WriteLine("Error: You cannot delete the root of a one node tree"); 187 | return false; 188 | } 189 | var mother = FindMother(root, value); 190 | if (value == mother.Left.Value) 191 | { 192 | mother.Left = null; 193 | return true; 194 | } 195 | else 196 | { 197 | mother.Right = null; 198 | return true; 199 | } 200 | } 201 | 202 | /// 203 | /// Delete a node when it has 1 child 204 | /// A method serves Delete() 205 | /// 206 | /// 207 | /// 208 | /// 209 | private static bool DeleteSingle(ref TreeNodeInt root, int value) 210 | { 211 | var current = root; 212 | 213 | if (root.Value == value) 214 | { 215 | if (root.Left != null) root = root.Left; 216 | else root = root.Right; 217 | return true; 218 | } 219 | 220 | var mother = FindMother(root, value); 221 | if (mother.Left.Value == value) 222 | { 223 | if (mother.Left.Left != null) mother.Left = mother.Left.Left; 224 | else mother.Left = mother.Left.Right; 225 | } 226 | else 227 | { 228 | if (mother.Right.Left != null) mother.Right = mother.Right.Left; 229 | else mother.Right = mother.Right.Right; 230 | } 231 | return true; 232 | } 233 | 234 | /// 235 | /// A mothod serves Delete() 236 | /// Delete a node when it has 2 children 237 | /// 238 | /// 239 | /// 240 | /// 241 | private static bool DeleteDouble(ref TreeNodeInt root, int value) 242 | { 243 | if (root.Value == value) 244 | { 245 | if (GetHeight(root.Left) > GetHeight(root.Right)) 246 | { 247 | root = FindLeftLargest(root); 248 | } 249 | else 250 | { 251 | root = FindRightSmallest(root); 252 | } 253 | return true; 254 | } 255 | 256 | var mother = FindMother(root, value); 257 | if (mother.Left.Value == value) 258 | { 259 | if (GetHeight(mother.Left.Left) > GetHeight(mother.Left.Right)) 260 | { 261 | mother.Left = FindLeftLargest(mother.Left); 262 | Console.WriteLine("FindLeftLargest"); 263 | } 264 | else 265 | { 266 | mother.Left = FindRightSmallest(mother.Left); 267 | Console.WriteLine("FindRightLargest"); 268 | } 269 | } 270 | else 271 | { 272 | if (GetHeight(mother.Right.Left) > GetHeight(mother.Right.Right)) 273 | { 274 | mother.Right = FindLeftLargest(mother.Right); 275 | Console.WriteLine("FindLeftLargest"); 276 | } 277 | else 278 | { 279 | mother.Right = FindLeftLargest(mother.Right); 280 | Console.WriteLine("FindRightLargest"); 281 | } 282 | } 283 | return true; 284 | } 285 | 286 | /// 287 | /// A method serves Delete() 288 | /// Find left largest node, break its original connections, put it on top 289 | /// 290 | /// 291 | /// 292 | /// 293 | private static TreeNodeInt FindLeftLargest(TreeNodeInt node) 294 | { 295 | var current = node.Left; 296 | var prev = current; 297 | if (current.Right == null) 298 | { 299 | current.Right = node.Right; 300 | } 301 | else 302 | { 303 | while (current.Right != null) 304 | { 305 | prev = current; 306 | current = current.Right; 307 | } 308 | //2 cases 309 | //1, left largest node has no child 310 | if (current.Left == null) 311 | { 312 | prev.Right = null; 313 | current.Left = node.Left; 314 | current.Right = node.Right; 315 | } 316 | //2, left largest node has node (a left child) 317 | else 318 | { 319 | prev.Right = current.Left; 320 | current.Left = node.Left; 321 | current.Right = node.Right; 322 | } 323 | } 324 | return current; 325 | } 326 | 327 | private static int GetHeight(TreeNodeInt node) 328 | { 329 | if (node.Left == null && node.Right == null) 330 | { 331 | return 1; 332 | } 333 | else 334 | { 335 | if (node.Left == null) 336 | { 337 | return GetHeight(node.Right) + 1; 338 | } 339 | else if (node.Right == null) 340 | { 341 | return GetHeight(node.Left) + 1; 342 | } 343 | else 344 | { 345 | if (GetHeight(node.Left) >= GetHeight(node.Right)) 346 | { 347 | return GetHeight(node.Left) + 1; 348 | } 349 | else 350 | { 351 | return GetHeight(node.Right) + 1; 352 | } 353 | } 354 | } 355 | } 356 | 357 | /// 358 | /// A method serves Delete() 359 | /// Find right smallest node, break its original connections, put it on top 360 | /// 361 | /// 362 | /// 363 | /// 364 | private static TreeNodeInt FindRightSmallest(TreeNodeInt node) 365 | { 366 | var current = node.Right; 367 | var prev = current; 368 | if (current.Left == null) 369 | { 370 | current.Left = node.Left; 371 | } 372 | else 373 | { 374 | while (current.Left != null) 375 | { 376 | prev = current; 377 | current = current.Left; 378 | } 379 | if (current.Right == null) 380 | { 381 | prev.Left = null; 382 | current.Left = node.Left; 383 | current.Right = node.Right; 384 | } 385 | else 386 | { 387 | prev.Left = current.Right; 388 | current.Left = node.Left; 389 | current.Right = node.Right; 390 | } 391 | } 392 | return current; 393 | } 394 | 395 | /// 396 | /// Find wanted value's mother node 397 | /// A method serves Delete() 398 | /// 399 | /// 400 | /// 401 | /// 402 | private static TreeNodeInt FindMother(TreeNodeInt root, int value) 403 | { 404 | var current = root; 405 | while (true) 406 | { 407 | if (current.Left.Value == value || current.Right.Value == value) 408 | { 409 | return current; 410 | } 411 | else 412 | { 413 | if (value < current.Value) 414 | { 415 | current = current.Left; 416 | } 417 | else 418 | { 419 | current = current.Right; 420 | } 421 | } 422 | } 423 | } 424 | 425 | /// 426 | /// Only open socket of delete 427 | /// delete action depend on 3 different cases 428 | /// 1.node has no child 429 | /// 2.node has 1 child 430 | /// 3.node has 2 children 431 | /// 1st case is straight forward 432 | /// 2st case use the child to replace itself 433 | /// 3st case use the Left Largest node or Right Smallest node to replace itself depend on balance status 434 | /// 435 | /// root node of a tree, use "ref" keyword 436 | /// the node you want to delete has this value 437 | /// 438 | public static bool Delete(ref TreeNodeInt root, int value) 439 | { 440 | var search = Search(root, value); 441 | var current = root; 442 | 443 | if (search == null) 444 | { 445 | Console.WriteLine("No such item in the tree"); 446 | return false; 447 | } 448 | 449 | if (search.Left == null && search.Right == null) 450 | { 451 | return DeleteLeaf(ref root, value); 452 | } 453 | else if (search.Left == null || search.Right == null) 454 | { 455 | return DeleteSingle(ref root, value); 456 | } 457 | else 458 | { 459 | return DeleteDouble(ref root, value); 460 | } 461 | } 462 | } 463 | 464 | /// 465 | /// a binary search tree node type, its value is an integer 466 | /// did not use generic types to make the program easier 467 | /// also because I don't know how to compare generic types 468 | /// 469 | public class TreeNodeInt 470 | { 471 | public int Value; 472 | public TreeNodeInt Left; 473 | public TreeNodeInt Right; 474 | 475 | public TreeNodeInt(int value, TreeNodeInt left, TreeNodeInt right) 476 | { 477 | Value = value; 478 | Left = left; 479 | Right = right; 480 | } 481 | } 482 | } 483 | -------------------------------------------------------------------------------- /YuGeneric/YuGeneric/BinaryTree.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.Generic 8 | { 9 | public class BinaryTreeNode 10 | { 11 | private T _value; 12 | private BinaryTreeNode _left; 13 | private BinaryTreeNode _right; 14 | 15 | public BinaryTreeNode(T value) 16 | { 17 | _value = value; 18 | _left = null; 19 | _right = null; 20 | } 21 | 22 | public BinaryTreeNode(T value, BinaryTreeNode left, BinaryTreeNode right) 23 | { 24 | _value = value; 25 | _left = left; 26 | _right = right; 27 | } 28 | 29 | public T Value 30 | { 31 | get 32 | { 33 | return _value; 34 | } 35 | set 36 | { 37 | _value = value; 38 | } 39 | } 40 | 41 | public BinaryTreeNode Left 42 | { 43 | get 44 | { 45 | return _left; 46 | } 47 | set 48 | { 49 | _left = value; 50 | } 51 | } 52 | 53 | public BinaryTreeNode Right 54 | { 55 | get 56 | { 57 | return _right; 58 | } 59 | set 60 | { 61 | _right = value; 62 | } 63 | } 64 | } 65 | 66 | public class BinaryTree 67 | { 68 | private BinaryTreeNode _root; 69 | 70 | public BinaryTree(BinaryTreeNode root) 71 | { 72 | _root = root; 73 | } 74 | 75 | public BinaryTree(T rootValue) 76 | { 77 | _root = new BinaryTreeNode(rootValue, null, null); 78 | } 79 | 80 | public BinaryTreeNode Root 81 | { 82 | get 83 | { 84 | return _root; 85 | } 86 | set 87 | { 88 | _root = value; 89 | } 90 | } 91 | 92 | public static void InOrder(BinaryTreeNode node){ 93 | if (node == null) return; 94 | InOrder(node.Left); 95 | Console.Write(node.Value + " "); 96 | InOrder(node.Right); 97 | } 98 | 99 | public static void PreOrder(BinaryTreeNode node) 100 | { 101 | if (node == null) return; 102 | Console.Write(node.Value + " "); 103 | PreOrder(node.Left); 104 | PreOrder(node.Right); 105 | } 106 | 107 | public static void PostOrder(BinaryTreeNode node) 108 | { 109 | if (node == null) return; 110 | PostOrder(node.Left); 111 | PostOrder(node.Right); 112 | Console.Write(node.Value + " "); 113 | } 114 | 115 | public static void PreOrderWithStack(BinaryTreeNode node) 116 | { 117 | Stack> stack = new Stack>(); 118 | BinaryTreeNode temp = node; 119 | if (temp != null) stack.Push(temp); 120 | 121 | while (!stack.IsEmpty()) 122 | { 123 | temp = stack.Top.Value; 124 | stack.Pop(); 125 | Console.Write(temp.Value + " "); 126 | if (temp.Right != null) 127 | { 128 | stack.Push(temp.Right); 129 | } 130 | if (temp.Left != null) 131 | { 132 | stack.Push(temp.Left); 133 | } 134 | } 135 | Console.WriteLine(); 136 | } 137 | 138 | /// 139 | /// "One Fish Bone At A Loop", it deals one "fishbone" at a loop-- 140 | /// a fish bone is a structure from top to most left child-- 141 | /// the fish bone is pushed follow the order "RightChild->Mother->RightChild->Mother"-- 142 | /// once a fish bone is finished, temp pointer will move to the latest right child|| 143 | /// structure: 144 | /// outer loop{ 145 | /// --inner loop1, stack stores up to most left child, temp to null 146 | /// --temp buffers Top and Pop it; 147 | /// --inner loop2, back track to latest node with right child, temp buffers the node, Top holds the right child 148 | /// --print the node, 149 | /// --if stack not empty, move temp pointer to the right child, start next outer loop 150 | /// --if stack is empty(node reaches root, with no right child), temp points null 151 | /// } 152 | /// 153 | /// 154 | public static void InOrderWithStack(BinaryTreeNode node) 155 | { 156 | var s = new Stack>(); 157 | var temp = node; 158 | while (temp != null) 159 | { 160 | while (temp != null) 161 | { 162 | if (temp.Right != null) { 163 | s.Push(temp.Right); 164 | } 165 | s.Push(temp); 166 | temp = temp.Left; 167 | } 168 | 169 | temp = s.Top.Value; 170 | s.Pop(); 171 | 172 | while (!s.IsEmpty() && temp.Right == null) 173 | { 174 | Console.Write(temp.Value + " "); 175 | temp = s.Top.Value; 176 | s.Pop(); 177 | } 178 | 179 | Console.Write(temp.Value + " "); 180 | 181 | if (!s.IsEmpty()) 182 | { 183 | temp = s.Top.Value; 184 | s.Pop(); 185 | } 186 | else 187 | { 188 | temp = null; 189 | } 190 | } 191 | } 192 | 193 | 194 | public static void PostOrderWithStack(BinaryTreeNode node){ 195 | var s = new Stack>(); 196 | var curr = node; 197 | var prev = node; 198 | 199 | while (curr != null) 200 | { 201 | while (curr.Left != null) 202 | { 203 | s.Push(curr); 204 | curr = curr.Left; 205 | } 206 | 207 | while (curr.Right == null || curr.Right == prev) 208 | { 209 | Console.Write(curr.Value + " "); 210 | prev = curr; 211 | if (s.IsEmpty()) return; 212 | curr = s.Top.Value; 213 | s.Pop(); 214 | } 215 | 216 | s.Push(curr); 217 | curr = curr.Right; 218 | } 219 | Console.WriteLine(); 220 | } 221 | 222 | /// 223 | /// 1.Firstly Join the root to queue, then start looping; 224 | /// 2.In loop, Buffer the queue Front, Leave it from queue, if it has child, join into queue, from left to right; 225 | /// 3.Break loop when queue is empty; 226 | /// Join items that need to priorly handled to the queue, based on queue's FIFO feature 227 | /// It will iterate through the tree top to down level by level 228 | /// 229 | /// 230 | public static void BreadthFirstTraversal(BinaryTreeNode root) 231 | { 232 | var q = new Queue>(); 233 | var temp = root; 234 | if (temp != null) 235 | { 236 | q.Join(temp); 237 | while (!q.IsEmpty()) 238 | { 239 | temp = q.Front.Value; 240 | q.Leave(); 241 | Console.Write(temp.Value + " "); 242 | if (temp.Left != null) 243 | q.Join(temp.Left); 244 | if (temp.Right != null) 245 | q.Join(temp.Right); 246 | } 247 | Console.WriteLine(); 248 | } 249 | } 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /YuGeneric/YuGeneric/HeapList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.Generic 8 | { 9 | public class HeapList 10 | { 11 | private List _list; 12 | 13 | public HeapList() 14 | { 15 | _list = new List(); 16 | } 17 | 18 | /// 19 | /// Insert an item to the heap 20 | /// swap if needed 21 | /// 22 | /// 23 | public void Insert(int item) 24 | { 25 | if (_list.Contains(item)) 26 | { 27 | Console.WriteLine("Error: Duplicate item"); 28 | return; 29 | } 30 | 31 | _list.Add(item); 32 | if (_list.Count() == 0) return; 33 | 34 | int motherIndex = 0; 35 | int childIndex = _list.Count() - 1; 36 | int buff=0; 37 | 38 | while (true) 39 | { 40 | motherIndex = (childIndex - 1) / 2; 41 | if (_list[childIndex] > _list[motherIndex]) 42 | { 43 | buff = _list[childIndex]; 44 | _list[childIndex] = _list[motherIndex]; 45 | _list[motherIndex] = buff; 46 | childIndex = motherIndex; 47 | } 48 | else break; 49 | } 50 | } 51 | 52 | /// 53 | /// Delete largest value of the heap which is the root 54 | /// 55 | /// 56 | public bool DeleteRoot() 57 | { 58 | //empty heap case 59 | if (_list.Count() == 0) 60 | { 61 | Console.WriteLine("Error: Empty heap"); 62 | return false; 63 | } 64 | 65 | //one item cases 66 | if (_list.Count() == 1) 67 | { 68 | _list.RemoveAt(0); 69 | return true; 70 | } 71 | 72 | //other cases 73 | _list[0] = _list[_list.Count() - 1]; 74 | _list.RemoveAt(_list.Count() - 1); 75 | //swap 76 | int motherIndex = 0; 77 | int childIndex = 1; 78 | int buff = 0; 79 | while (true) 80 | { 81 | if (childIndex < _list.Count() - 1) 82 | { 83 | Console.WriteLine("both in range"); 84 | if (_list[motherIndex] < Math.Max(_list[childIndex], _list[childIndex + 1])) 85 | { 86 | 87 | buff = _list[motherIndex]; 88 | childIndex = MaxIndex(childIndex); 89 | _list[motherIndex] = _list[childIndex]; 90 | _list[childIndex] = buff; 91 | 92 | motherIndex = childIndex; 93 | childIndex = motherIndex * 2 + 1; 94 | } 95 | else break; 96 | } 97 | else if (childIndex == _list.Count() - 1) 98 | { 99 | if (_list[motherIndex] < _list[childIndex]) 100 | { 101 | buff = _list[motherIndex]; 102 | _list[motherIndex] = _list[childIndex]; 103 | _list[childIndex] = buff; 104 | } 105 | break; 106 | } 107 | else break; 108 | } 109 | return true; 110 | } 111 | 112 | /// 113 | /// returns the index of the biggest node in the 2 children node 114 | /// serves DeleteRoot() 115 | /// 116 | /// 117 | /// 118 | public int MaxIndex(int childIndex) 119 | { 120 | return _list.FindIndex(x => x == Math.Max(_list[childIndex], _list[childIndex + 1])); 121 | } 122 | 123 | /// 124 | /// print the whole heap 125 | /// 126 | public void Print() 127 | { 128 | foreach (int item in _list) 129 | Console.Write(item + " "); 130 | Console.Write("\n"); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /YuGeneric/YuGeneric/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Yu.DataStructure.Generic")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Yu.DataStructure.Generic")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("839eff68-bc7d-4627-acac-d839976168fa")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /YuGeneric/YuGeneric/Queue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.Generic 8 | { 9 | public class QueueNode 10 | { 11 | private T _value; 12 | private QueueNode _next; 13 | 14 | public QueueNode(){ 15 | } 16 | 17 | public QueueNode(T value) 18 | { 19 | _value = value; 20 | } 21 | 22 | public T Value{ 23 | get 24 | { 25 | return _value; 26 | } 27 | set 28 | { 29 | _value = value; 30 | } 31 | } 32 | 33 | public QueueNode Next 34 | { 35 | get 36 | { 37 | return _next; 38 | } 39 | set 40 | { 41 | _next = value; 42 | } 43 | } 44 | } 45 | 46 | public class Queue 47 | { 48 | private QueueNode _front; 49 | private QueueNode _rear; 50 | 51 | public QueueNode Front 52 | { 53 | get 54 | { 55 | return _rear; 56 | } 57 | set 58 | { 59 | _rear = value; 60 | } 61 | } 62 | 63 | public bool IsEmpty() 64 | { 65 | if (_front == null && _rear == null) 66 | { 67 | return true; 68 | } 69 | else 70 | { 71 | return false; 72 | } 73 | } 74 | 75 | public int Count() 76 | { 77 | int count = 0; 78 | var current = _front; 79 | while (current != null) 80 | { 81 | count++; 82 | current = current.Next; 83 | } 84 | return count; 85 | } 86 | 87 | public void Join(QueueNode node) 88 | { 89 | if (this.IsEmpty()) 90 | { 91 | _front = node; 92 | _rear = node; 93 | } 94 | else 95 | { 96 | node.Next = _front; 97 | _front = node; 98 | } 99 | } 100 | 101 | public void Join(T value) 102 | { 103 | this.Join(new QueueNode(value)); 104 | } 105 | 106 | public bool Leave() 107 | { 108 | if (this.IsEmpty()) 109 | { 110 | return false; 111 | } 112 | if (this.Count() == 1) 113 | { 114 | _front = null; 115 | _rear = null; 116 | return true; 117 | } 118 | 119 | var current = _front; 120 | while (current.Next != _rear) 121 | { 122 | current = current.Next; 123 | } 124 | current.Next = null; 125 | _rear = current; 126 | return true; 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /YuGeneric/YuGeneric/Stack.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu.DataStructure.Generic 8 | { 9 | public class Stack 10 | { 11 | private StackNode _top; 12 | 13 | public StackNode Top 14 | { 15 | get 16 | { 17 | return _top; 18 | } 19 | set 20 | { 21 | _top = value; 22 | } 23 | } 24 | 25 | public void Push(StackNode node) 26 | { 27 | if (_top == null) 28 | _top = node; 29 | else 30 | { 31 | node.Next = _top; 32 | _top = node; 33 | } 34 | } 35 | 36 | public void Push(T value) 37 | { 38 | var node = new StackNode(value); 39 | this.Push(node); 40 | } 41 | 42 | public void Pop() 43 | { 44 | if (_top == null) 45 | return; 46 | else 47 | { 48 | _top = _top.Next; 49 | } 50 | } 51 | 52 | public bool IsEmpty() 53 | { 54 | if (_top == null) 55 | return true; 56 | else 57 | return false; 58 | } 59 | } 60 | 61 | public class StackNode 62 | { 63 | private T _value; 64 | private StackNode _next; 65 | 66 | public StackNode() 67 | { 68 | } 69 | 70 | public StackNode(T value){ 71 | _value = value; 72 | _next = null; 73 | } 74 | 75 | public T Value 76 | { 77 | get 78 | { 79 | return _value; 80 | } 81 | set 82 | { 83 | _value = value; 84 | } 85 | } 86 | 87 | public StackNode Next 88 | { 89 | get 90 | { 91 | return _next; 92 | } 93 | set 94 | { 95 | _next = value; 96 | } 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /YuGeneric/YuGeneric/TestClass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Yu 8 | { 9 | public class TestClass 10 | { 11 | public static TestObj ReturnObj() 12 | { 13 | var to = new TestObj(); 14 | return to; 15 | } 16 | } 17 | 18 | public class TestObj 19 | { 20 | public int i; 21 | public string str; 22 | 23 | public TestObj() 24 | { 25 | i = 10; 26 | str = "aaa"; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /YuGeneric/YuGeneric/Yu.DataStructure.Generic.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {1A09F2E3-F75D-4A39-82D4-CE5897B3DB5C} 8 | Library 9 | Properties 10 | Yu 11 | Yu.DataStructure.Generic 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 59 | -------------------------------------------------------------------------------- /YuGeneric/`Notes/BinaryTreePostOrderTraversalWithStack.txt: -------------------------------------------------------------------------------- 1 | Post Order Traverasl With Stack 2 | --2 buffers, 1 stack 3 | --2 tiers of loops 4 | --tier 0 loop, deals a left side top down straight line, contains 2 tier 1 loops 5 | --prints the end node of the straight line 6 | --use stack to store up to the latest mother node with a right child 7 | --use temp1 to buffer the right child as root of next turn 8 | ------------------------------------------------------------------------------------------------------------------------------------- 9 | --tier 1, 1st loop 10 | --temp1 reaches the end node of straight line 11 | --stack stores up to the mother of this end node 12 | ------------------------------------------------------------------------------------------------------------------------------------- 13 | --tier 1, 2nd loop 14 | --use stack and temp1 to back track -> through nodes without right child -> reaches mother with right child 15 | buffer mother in temp1; buffer left child in temp2 16 | ------------------------------------------------------------------------------------------------------------------------------------- 17 | --temp1 (mother node with right child) push back to stack, temp1 is now the right child 18 | ------------------------------------------------------------------------------------------------------------------------------------- 19 | --temp1 is the main processing buffer 20 | --temp2 always look like a left child, but it is actually the previous content of temp1 21 | --loop2 uses 2 conditions, 1st means loop only stop at mother with right child 22 | --2nd condition means loop will continue if temp1 is poping the node from last tier straight line 23 | --so when temp1 jumped back to last straight line, loop continues 24 | 25 | -------------------------------------------------------------------------------- /notes/BalancedBinaryTreeSearchComplexity.md: -------------------------------------------------------------------------------- 1 | #Search time complexity for a balanced binary tree 2 | (this note is not rigorous, just to give a general idea) 3 | * Firstly, refer to Big O Notation. See [A beginner's guide to Big O notation(Rob Bell)](https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation) 4 | * for a balanced binary tree, generally its search time complexity of the worst case should be equal to the max-height of the tree. 5 | * counting from the root, the number of nodes at each level should be {1,2,4,8,...,2^h}, which "h" is the max-height. 6 | 7 | |nodes at each lvl |total nodes at each lvl|height | 8 | |--------------------:|----------------------:|-------:| 9 | |1 |1 |0 | 10 | |2 |3 |1 | 11 | |4 |7 |2 | 12 | |8 |15 |3 | 13 | |... |... |... | 14 | |2^h |2^(h+1)-1 |h | 15 | 16 | Let's say total nodes is "n", time complexity is "h" 17 | ``` 18 | 2^(h+1) - 1 = n-1 19 | 2^(h+1) = n-1 20 | 2^(h+1) = n //1 here is a low order constant, ignore it 21 | log 2 (2^(h+1)) = log 2 n 22 | h+1 = log(n) //ignore 1 on the left 23 | h = log(n) 24 | ``` 25 | 26 | Thus we say the time complexity would be O(log(n)) 27 | Again this is not rigorous, refer to CLRS, generally people use mathematical induction to prove time complexity, although I could 28 | not do it for now :( 29 | Please comment if you think you can correct or improve this. 30 | -------------------------------------------------------------------------------- /notes/BubbleSort.md: -------------------------------------------------------------------------------- 1 | #Bubble Sort 2 | * **Summary** 3 | treat 2 items as a bubble, swap if needed, and move on unitil reach the end. Do this again and again until no swapping happens.

4 | * **Time complexity O(N^2)** 5 | while{for{}}. 6 | -------------------------------------------------------------------------------- /notes/GraphAndDijkstrasAlgorithm.md: -------------------------------------------------------------------------------- 1 | Graph and Dijkstra's Algorithm 2 | ---------------------------- 3 | [[Graph code](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/Graph.cs)] 4 | [[Dijkstra's Algorithm code](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/DijkstrasAlgorithm.cs)] 5 |
    6 |
  • 7 | Summary 8 |
      9 |
    • 10 | Graph
      11 |

      Graph is a set of Nodes that each Node could point to or be pointed by any other Nodes. 12 | The connection between each Nodes are called Edges, Edge has a cost property. The cost of each edge may vary. 13 | Edges also has direction, from A to B and from B to A are different. 14 | In those cases that edges do not have directions, it should be treated like A to B and B to A are all existed and their cost are the same.

      15 |

      In my code the Graph class is based on List of LinkedList. Each LinkedList in the List represents a node in the graph. 16 | Each Element in the LinkedList possesses 2 properties, a node mark (a letter) and a cost, means the destination and the Edge cost. 17 | The first element of the LinkedList represent the Node itself, and its cost is 0.

      18 |
    • 19 |
    • 20 | Dijkstra's Algorithm
      21 |

      Dijkstra's algorithm calculate the shortest routes of one start Node to all other Nodes.

      22 |
    • 23 |
    24 |
  • 25 |
  • 26 | Dijkstra's logic 27 |
      28 |
    1. 29 | Declare a dictionary d to store the current shortest distance of each destination node.
      30 | Declare a dictionary s to store the status of each node that if its shortest distance is final decision.
      31 |
    2. 32 |
    3. 33 | Set start node's distance to 0 , status to true (is final) ; Set all other node's distance to infinity (practically a very big number) , status to false (not final). 34 |
    4. 35 |
    5. 36 | Initially "current" starts from the start node (as in the input parameter). 37 | Take the current node as a temporary start node, update all the node's current distances (in d) by picking the smaller value from its old value and the (current start node's distance(in d) plus destiny node's edge cost). 38 |
    6. 39 |
    7. 40 | In all the node's that status are not final yet (in s), find the one with smallest distance (in d). Set it as next turn current node, and set its status to final (true). 41 |
    8. 42 |
    9. 43 | Repeat 2 steps above, until all nodes' status (in s) are final (true). 44 |
    10. 45 |
    46 |
  • 47 |
  • 48 | Example
    49 | (Under construction). 50 | 51 |
  • 52 |
53 | 54 | 55 | -------------------------------------------------------------------------------- /notes/Heap.md: -------------------------------------------------------------------------------- 1 | #Heap 2 | [[Full code]](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/Yu.DataStructure.NonGeneric/Yu.DataStructure.NonGeneric/Heap.cs) 3 | 4 | #Summary 5 | Priority Queue is a data structure that when you pop you get either the maximum or minimum depending. 6 | 7 | Heap is an implementation of priority queue which provides good time complexity "O(logn)" while pushing and poping. 8 | * Heap is a self balanced binary tree, which means the differences of heights between any two leaves would be less or equal to 1. 9 | * Heap has a feature that at any level, a node is always larger(or smaller depending) than its children. 10 | * In a heap, no matter what order you use to push items into heap, the heap will re-construct to make sure it meets the 2 11 | requirements above. 12 | 13 | #Logic and code snippet 14 | * **Implementing using generic.List** 15 | A heap is just a logical tree, we do not have to implement it using a real tree. In this circumstance, a List (vector) is 16 | more suitable that its random access feature makes operations much faster. 17 | ```c# 18 | public class Heap 19 | { 20 | private List _list; 21 | 22 | public Heap() 23 | { 24 | _list = new List(); 25 | } 26 | ``` 27 | * **Example Heap tree** 28 | ![heap_tree](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/Images/HeapTree.PNG?raw=true) 29 | * **Example Heap using List** 30 | ![heap_list](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/Images/HeapList.PNG?raw=true) 31 | 32 | * **Indexing** 33 | From the heap list image above we can see that 34 | + leftChildIndex = parentIndex * 2 + 1 35 | + rightChildIndex = parentIndex * 2 + 2 36 | Or we can say: 37 | + parentIndex = (childIndex - 1) / 2 38 | (Works for both children, because in Integer Division, 4/2 and 5/2 gave the same result) 39 | 40 | * **Insert() method** 41 | Push, Insert an item to heap. Key point is to make sure the heap meets heap's requirements. 42 | 1. Add an item to the end of the list. 43 | 2. If its value is larger than its parent's value, swap them. 44 | 3. Repeat step 2 above, until this value's parent value no longer smaller than itself. 45 | ```c# 46 | public void Insert(int item) 47 | { 48 | //duplicate entry verification 49 | if (_list.Contains(item)) 50 | { 51 | Console.WriteLine("Error: Duplicate item"); 52 | return; 53 | } 54 | 55 | _list.Add(item); 56 | 57 | //no further operation needed if only 1 item in the heap after insertion 58 | if (_list.Count() == 1) return; 59 | 60 | //--common cases, heap wasn't empty before insertion, needs reconstruction-- 61 | int motherIndex = 0; 62 | int childIndex = _list.Count() - 1; 63 | int buff = 0; 64 | 65 | while (true) 66 | { 67 | motherIndex = (childIndex - 1) / 2; 68 | if (_list[childIndex] > _list[motherIndex]) 69 | { 70 | buff = _list[childIndex]; 71 | _list[childIndex] = _list[motherIndex]; 72 | _list[motherIndex] = buff; 73 | childIndex = motherIndex; 74 | } 75 | else break; 76 | } 77 | //--reconstruction done-- 78 | } 79 | ``` 80 | * **DeleteRoot() method** 81 | Pop, returns the root value, and delete the root node. It also needs to make sure the heap still meets heap's requirements. 82 | 1. Swap root value with the last node's value, remove the last node. 83 | 2. Swap the new root value with its larger child. 84 | 3. Repeat step 2 above, until it reaches leaf or got no children that larger than itself. 85 | ```c# 86 | public int DeleteRoot() 87 | { 88 | int result; 89 | 90 | //if heap is empty, return null 91 | if (_list.Count() == 0) 92 | { 93 | Console.WriteLine("Error: Empty heap"); 94 | return null; 95 | } 96 | 97 | //if heap has 1 item, just return it 98 | if (_list.Count() == 1) 99 | { 100 | result = _list[0]; 101 | _list.RemoveAt(0); 102 | return result; 103 | } 104 | 105 | //--common cases that items are more than 1, need reconstruction-- 106 | //swap root with tail 107 | result = _list[0]; 108 | _list[0] = _list[_list.Count() - 1]; 109 | _list.RemoveAt(_list.Count() - 1); 110 | 111 | int motherIndex = 0; 112 | int childIndex = 1; 113 | int buff = 0; 114 | while (true) 115 | { 116 | //if not reaching leaf, both children indices are within range 117 | if (childIndex < _list.Count() - 1) 118 | { 119 | //if mother smaller than any of the children, swap. Otherwise, break loop. 120 | if (_list[motherIndex] < Math.Max(_list[childIndex], _list[childIndex + 1])) 121 | { 122 | 123 | buff = _list[motherIndex]; 124 | childIndex = MaxIndex(childIndex); 125 | _list[motherIndex] = _list[childIndex]; 126 | _list[childIndex] = buff; 127 | 128 | motherIndex = childIndex; 129 | childIndex = motherIndex * 2 + 1; 130 | } 131 | else break; 132 | } 133 | //if only left child index is within range, just swap it with mother if needed 134 | else if (childIndex == _list.Count() - 1) 135 | { 136 | if (_list[motherIndex] < _list[childIndex]) 137 | { 138 | buff = _list[motherIndex]; 139 | _list[motherIndex] = _list[childIndex]; 140 | _list[childIndex] = buff; 141 | } 142 | break; 143 | } 144 | //if itself reaches leaf, just break the loop 145 | else break; 146 | } 147 | //--reconstuction done-- 148 | return result; 149 | } 150 | ``` 151 | #Time complexity 152 | Push and Pop are both O(log(n)) 153 | See [balanced binary tree's search time complexity](https://github.com/scottszb1987/DataStructureAndAlgorithms/blob/master/notes/BalancedBinaryTreeSearchComplexity.md) 154 | -------------------------------------------------------------------------------- /notes/HeapSort.md: -------------------------------------------------------------------------------- 1 | #Heap Sort 2 | * **Summary** 3 | Use the "root always largest" feature of heap to sort.
4 | * **Logic** 5 | + Insert all items to the heap 6 | + Delete(return) the root value back to the array. 7 | * **Time complexity** 8 | O(NlogN). Every Delete() of heap costs logN, thus N items cost NlogN. 9 | -------------------------------------------------------------------------------- /notes/InsertionSort.md: -------------------------------------------------------------------------------- 1 | #Insertion Sort 2 | * **Summary** 3 | iterate to out-of-order item, insert it to its right position by shift other items from that position, and go on.

4 | * **Time complexity O(N^2)** 5 | for{for{}} 6 | -------------------------------------------------------------------------------- /notes/MergeSort.md: -------------------------------------------------------------------------------- 1 | #Merge Sort 2 | * **Summary** 3 | Based on Merge(). Merge method merges 2 sorted array into one sorted array. Merge Sort breaks array into smallest chunks and recursively implement Merge. 4 | * **Logic** 5 | + Merge() 6 | Break array into 2 sub arrays evenly 7 | - 1st loop: put smaller value of either left or right sub array into the temporary array, until one array runs out 8 | (after the 1st loop ends, there must be at least 1 sub array runs out) 9 | - 2nd loop: in case left sub array does not run out (which right sub array does), add its items to temporary array 10 | - 3rd loop: in case right sub array has items and left runs out, add its items to temporary array 11 | + MergeSort() 12 | - Break array from "first" to "last" into 2 sub array 13 | - MergeSort left sub-array 14 | - MergeSort right sub-array 15 | - Merge() the array back together again 16 | * **Remark** 17 | Merge() function is based on the assumption that the 2 sub-arrays are sorted, so we recursively break the array into smallest chunks (so that sub-arrays must be sorted), and Merge() them back to original array 18 | * **Time complexity O(NlogN)** 19 | Because Merge is O(N) and its breaking(like a binary tree) is O(logN). 20 | -------------------------------------------------------------------------------- /notes/QuickSort.md: -------------------------------------------------------------------------------- 1 | Quicksort 2 |
    3 |
  • 4 | Summary
    5 | Pick a pivot value, put smaller items to its left, put larger items to its right. Do the same way to the left part and to the right part recursively until the chunk size is 2. 6 |
  • 7 |
  • 8 | Logic
    9 | Pick the first item as the pivot
    10 | Put all items smaller than pivot to the left and put all items larger to the right by swapping
    11 | Swap pivot with the smallest right item to place pivot in between
    12 | Do this again to the left part and right part recursively until chunk size is 2
    13 |
  • 14 |
  • 15 | Example
    16 | P for pivot, I for inc(index increment), D for dec(index decrement)
    17 | 18 | 19 | 20 |
    7382560194
    PI D
    21 | Initial case, pivot -> 7, inc -> 3, dec -> 4
    22 | 7 3 8 2 5 6 0 1 9 4
    23 | 24 | 25 | 26 |
    7382560194
    P I D
    27 | Inc -> 8 (8 > pivot); dec -> 4 (4 < pivot)
    28 | 29 | 30 | 31 |
    7342560198
    P DI
    32 | Swap 8 and 4 ; inc -> 9, dex -> 1 ; inc > dec (not the value they point, but their index), loop ends.
    33 | 34 | 35 | 36 |
    1342560798
    P
    37 | Now loop at pivot, coz pivot 7 > dec 1, swap 7 and 1 (Now we can see that left of 7 are all smaller than 7, right of 7 are all larger)
    38 | 39 | 40 | 41 |
    1342560 7 98
    PI D
    42 | Now treat left of 7 as a sub-array, and right of 7 as another sub-array, look at left sub-array first, implement same method
    43 | Pivot -> 1 , inc -> 3, dec -> 0
    44 | 45 | 46 | 47 |
    1342560 7 98
    PI D
    48 | Inc still at 3 (3 > pivot), dec still at 0 (0 < pivot)
    49 | 50 | 51 | 52 |
    1042563 7 98
    PDI D
    53 | Swap 3 and 0 ; inc -> 4, dec -> 0 ; inc > dec , loop ends.
    54 | 55 | 56 | 57 |
    0142563 7 98
    P
    58 | Pivot 1 > dec 0, swap 1 and 0
    59 | 60 | 61 | 62 |
    0 1 42563 7 98
    PI D
    63 | Left of pivot 1 is only 0, no sorting needed ; look at right sub-array 4 to 3
    64 | Pivot -> 4, inc -> 2, dec -> 3
    65 | 66 | 67 | 68 |
    0 1 42563 7 98
    P I D
    69 | Inc -> 5 , dec -> 3
    70 | 71 | 72 | 73 |
    0 1 42365 7 98
    P DI
    74 | Swap 5 and 3 ; inc -> 6 , dec -> 3 ; inc > dec , loop ends.
    75 | 76 | 77 | 78 |
    0 1 32465 7 98
    P
    79 | Pivot 4 > dec 3 , swap 4 and 3
    80 | 81 | 82 | 83 |
    0 1 32 4 65 7 98
    PID
    84 | 3 and 2 is left sub-array, 6 and 5 is right sub-array. Look at left sub-array first.
    85 | Only 2 items, inc and dec are same and not movable. Pivot -> 3 , Inc = Dec ->2.
    86 | 87 | 88 | 89 |
    0 1 2 3 4 5 6 7 98
    PID
    90 | Pivot 3 > dec 2, Swap 3 and 2.
    91 | Look at right sub-array 6 and 5, same situation, swap 6 and 5
    92 | Back to earliest right sub-array [9 8]
    93 | 94 | 95 |
    0 1 2 3 4 5 6 7 8 9
    96 | Same situation, swap 9 and 8. Array sorted.
    97 |
  • 98 |
  • 99 | Time Complexity
    100 | O(NlogN) Pretty much like other recursive method, or like a tree, in my opinion
    101 |
  • 102 |
103 | -------------------------------------------------------------------------------- /notes/RadixSort.md: -------------------------------------------------------------------------------- 1 | Radix Sort 2 |
    3 |
  • Summary
    4 | A sorting method without comparison. Sort from smallest digit to largest digit. 5 | This is NOT a binary sort! Place in here temporarily. 6 |
  • 7 |
  • Logic
    8 |
      9 |
    1. declare a queue array, array length is 10 (0-9).
    2. 10 |
    3. 1st tier loop, loop from smallest digit to largest digit, this loop contains 2 2nd tier loops below
    4. 11 |
    5. 2nd tier 1st loop, iterate through all items in input data array. Repeatedly enqueue the item into the queue that the queue's index is the current processing digit. 12 | (At this step all items are stored in the queue array based on current processing digit)
    6. 13 |
    7. 2nd tier 2nd loop, iterate through the queue array. For each queue in the queue array that has items, dequeue them back to the data array. 14 | (Now the data array is restored in an order of sorting by current processing digit, and the queue array is empty)
    8. 15 |
    9. Back to 1st tier loop, 10 times the factor so we move 1 digit to the left. Carry on to next turn.
    10. 16 |
    17 |
  • 18 |
  • Example
    19 | data array {5, 37, 1, 61, 11, 59, 48, 19}
    20 | Initially we have this data array, we wanna sort it. 21 | 22 | 23 | 24 | 25 | 26 |
    0123456789
    15374859
    6119
    11
    27 | Firstly we look at least significant bit, digit 1. Enqueue the data array to the queue array based on digit 1.
    28 | data array {1, 61, 11, 5, 37, 48, 59, 19}
    29 | After the queue array is restored, dequeue them back to the data array, now digit 1 is sorted.
    30 | 31 | 32 | 33 | 34 |
    0123456789
    11137485961
    519
    35 | Now move to digit 2, enqueue data array into queue array based on digit 2.
    36 | data array {1, 5, 11, 19, 37, 48, 59, 61}
    37 | After the queue array is restored, dequeue them back to the data array, now digit 2 is sorted.
    38 | (the data array is pretty much sorted, but we still need to continue in case that digit 3 is existed)
    39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 |
    0123456789
    1
    5
    11
    19
    37
    48
    59
    61
    50 | Same old, 3rd digit. Now only '0' in digit 3 has items.
    51 | data array {1, 5, 11, 19, 37, 48, 59, 61}
    52 | Dequeue them back to data array, data array is sorted.
    53 |
  • 54 |
  • 55 | Time Complexity
    56 | O(KN), for K digits we have K constant loops. For each loop, we iterate through whole data array, so N. Thus K*N.
    57 | O(KN) is very fast, but need extra space, and queue operations are not counted in the performance analysis. The actually performance very much depend on how you implement
    58 |
  • 59 |
60 | -------------------------------------------------------------------------------- /notes/SelectionSort.md: -------------------------------------------------------------------------------- 1 | #Selection Sort 2 | * **Summary** 3 | swap current item with currently smallest item, and move 1 item forward.

4 | * **pseudo** 5 | ``` 6 | for (i = 0; i < array.Length; i++){ 7 | swap(array[i], Min(array[i to array.Length])); 8 | } 9 | ``` 10 | * **Time complexity O(N^2)** 11 | for{for{}} 12 | -------------------------------------------------------------------------------- /notes/SortingAlgorithms/QuickSort.md: -------------------------------------------------------------------------------- 1 | #Quick Sort 2 | ##Source code 3 | [https://github.com/scottszb1987/DataStructureAndAlgorithmsInCSharp/blob/master/SortingAlgorithms/SortingAlgorithms/BinarySort.cs](https://github.com/scottszb1987/DataStructureAndAlgorithmsInCSharp/blob/master/SortingAlgorithms/SortingAlgorithms/BinarySort.cs) 4 | ##Summary 5 | Quick sort algorithm using Lomuto partition scheme. 6 | ##Detail 7 | + Assuming that we have an unsorted integer array ```nums``` with items ```{ 3, 9, 2, 5, 6, 4, 11, 7, 12 }``` . We want to sort it in an ascending order. 8 | + Here is the general code for quick sort: 9 | ```c# 10 | public static void QuickSort(int[] nums, int low, int high) 11 | { 12 | if (low < high) 13 | { 14 | int pivot = Partition(nums, low, high); 15 | QuickSort(nums, low, pivot - 1); 16 | QuickSort(nums, pivot + 1, high); 17 | } 18 | } 19 | ``` 20 | - ```public static void QuickSort(int[] nums, int low, int high){}``` 21 | This method contains 3 argument. ```int[] nums``` is the input integer array to be sorted, ```int low``` represents the start index of current sub-array, ```int high``` represents the end index of current sub-array. 22 | - ```if (low < high){}``` 23 | At the some stages of the recursion, low may equal to high, that's where the recursion branch ends. Only if there are at least 2 items in the sub-array, the recursion may go deeper. 24 | - ```int pivot = Partition(nums, low, high);``` 25 | This ```Partition``` method is the core of quick sort. 26 | ... to be continued... 27 | 28 | --------------------------------------------------------------------------------