├── .gitignore ├── DataStructure └── 01-Heap │ ├── 01-Heap.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata │ ├── 01-Heap │ ├── Heap.swift │ └── main.swift │ └── README.md ├── LICENSE ├── LeetCode ├── .vscode │ └── launch.json ├── 001-Two-Sum │ ├── 001-Two-Sum.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 007-Reverse-Integer │ ├── 007-Reverse-Integer.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 009-Palindrome-Number │ ├── 009-Palindrome-Number.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 013-Roman-to-Integer │ ├── 013-Roman-to-Integer.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 014-Longest-Common-Prefix │ ├── 014-Longest-Common-Prefix.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 02.03-delete-middle-node-lcci │ └── delete-middle-node-lcci.go ├── 020-Valid-Parentheses │ ├── 020-Valid-Parentheses.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 021-Merge-Two-Sorted-Lists │ ├── 021-Merge-Two-Sorted-Lists.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 026-Remove-Duplicates-from-Sorted-Array │ ├── 026-Remove-Duplicates-from-Sorted-Array.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 027-Remove-Element │ ├── 027-Remove-Element.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 028-Implement-strStr() │ ├── 028-Implement-strStr().playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 035-Search-Insert-Position │ ├── 035-Search-Insert-Position.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 038-Count-and-Say │ ├── 038-Count-and-Say.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 053-Maximum-Subarray │ ├── 053-Maximum-Subarray.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 054-Spiral-Matrix │ ├── 054-Spiral-Matrix.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 058-Length-of-Last-Word │ ├── 058-Length-of-Last-Word.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 066-Plus-One │ ├── 066-Plus-One.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 067-Add-Binary │ ├── 067-Add-Binary.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 069-Sqrt(x) │ ├── 069-Sqrt(x).playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 070-Climbing-Stairs │ ├── 070-Climbing-Stairs.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 083-Remove-Duplicates-from-Sorted-List │ ├── 083-Remove-Duplicates-from-Sorted-List.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 088-Merge-Sorted-Array │ ├── 088-Merge-Sorted-Array.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 100-Same-Tree │ ├── 100-Same-Tree.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 101-Symmetric-Tree │ ├── 101-Symmetric-Tree.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 104-Maximum-Depth-of-Binary-Tree │ ├── 104-Maximum-Depth-of-Binary-Tree.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 107-Binary-Tree-Level-Order-Traversal-II │ ├── 107-Binary-Tree-Level-Order-Traversal-II.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 108-Convert-Sorted-Array-to-Binary-Search-Tree │ ├── 108-Convert-Sorted-Array-to-Binary-Search-Tree.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 110-Balanced-Binary-Tree │ ├── 110-Balanced-Binary-Tree.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 118-Pascal's-Triangle │ ├── 118-Pascal's-Triangle.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 498-Diagonal-Traverse │ ├── 498-Diagonal-Traverse.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 509-Fibonacci-Number │ ├── 509-Fibonacci-Number.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 724-Find-Pivot-Index │ ├── 724-Find-Pivot-Index.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── 747-Largest-Number-At-Least-Twice-of-Others │ ├── 747-Largest-Number-At-Least-Twice-of-Others.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ └── README.md ├── PLACE_HOLDER │ ├── NO.-PROBLEM_NAME.playground │ │ ├── Contents.swift │ │ └── contents.xcplayground │ ├── README.md │ └── new-lc.sh └── delete-middle-node-lcci ├── README.md ├── README_CN.md ├── Search ├── 01-BinarySearch-Iteratively │ ├── 01-BinarySearch-Iteratively.xcodeproj │ │ ├── project.pbxproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ ├── xcshareddata │ │ │ │ └── IDEWorkspaceChecks.plist │ │ │ └── xcuserdata │ │ │ │ └── kingcos.xcuserdatad │ │ │ │ └── UserInterfaceState.xcuserstate │ │ └── xcuserdata │ │ │ └── kingcos.xcuserdatad │ │ │ └── xcschemes │ │ │ └── xcschememanagement.plist │ ├── 01-BinarySearch-Iteratively │ │ └── main.swift │ └── README.md └── 02-BinarySearch-Recursively │ ├── 02-BinarySearch-Recursively.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ ├── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcuserdata │ │ │ └── kingcos.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ └── kingcos.xcuserdatad │ │ └── xcschemes │ │ └── xcschememanagement.plist │ ├── 02-BinarySearch-Recursively │ └── main.swift │ └── README.md └── Sort ├── 01-SelectionSort ├── 01-SelectionSort.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ ├── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcuserdata │ │ │ └── kingcos.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ └── kingcos.xcuserdatad │ │ └── xcschemes │ │ └── xcschememanagement.plist ├── 01-SelectionSort │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 02-InsertionSort ├── 02-InsertionSort.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ ├── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcuserdata │ │ │ └── kingcos.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ └── kingcos.xcuserdatad │ │ └── xcschemes │ │ └── xcschememanagement.plist ├── 02-InsertionSort │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 03-InsertionSort-Advanced ├── 03-InsertionSort-Advanced.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ ├── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcuserdata │ │ │ └── kingcos.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ └── kingcos.xcuserdatad │ │ └── xcschemes │ │ └── xcschememanagement.plist ├── 03-InsertionSort-Advanced │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 04-BubbleSort ├── 04-BubbleSort.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ │ └── kingcos.xcuserdatad │ │ └── xcschemes │ │ └── xcschememanagement.plist ├── 04-BubbleSort │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 05-ShellSort ├── 05-ShellSort.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ ├── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ │ └── xcuserdata │ │ │ └── kingcos.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ └── kingcos.xcuserdatad │ │ └── xcschemes │ │ └── xcschememanagement.plist ├── 05-ShellSort │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 06-MergeSort ├── 06-MergeSort.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ └── xcuserdata │ │ └── kingcos.xcuserdatad │ │ └── xcschemes │ │ └── xcschememanagement.plist ├── 06-MergeSort │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 07-MergeSort-Advanced ├── 07-MergeSort-Advanced.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── 07-MergeSort-Advanced │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 08-MergeSort-BottomUp ├── 08-MergeSort-BottomUp.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── 08-MergeSort-BottomUp │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 09-QuickSort ├── 09-QuickSort.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── 09-QuickSort │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 10-QuickSort-Randomized ├── 10-QuickSort-Randomized.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── 10-QuickSort-Randomized │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 11-QuickSort-2-Way ├── 11-QuickSort-2-Way.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── 11-QuickSort-2-Way │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 12-QuickSort-3-Way ├── 12-QuickSort-3-Way.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── 12-QuickSort-3-Way │ ├── TestHelper.swift │ └── main.swift └── README.md ├── 13-HeapSort ├── 13-HeapSort.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata ├── 13-HeapSort │ ├── Heap.swift │ ├── TestHelper.swift │ └── main.swift └── README.md └── 14-HeapSort-Heapify ├── 14-HeapSort-Heapify.xcodeproj ├── project.pbxproj └── project.xcworkspace │ └── contents.xcworkspacedata ├── 14-HeapSort-Heapify ├── Heap.swift ├── TestHelper.swift └── main.swift └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## macOS 2 | .DS_Store 3 | 4 | ## Playgrounds 5 | timeline.xctimeline 6 | playground.xcworkspace -------------------------------------------------------------------------------- /DataStructure/01-Heap/01-Heap.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 84E24F8E1E8102D300CBC3F2 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E24F8D1E8102D300CBC3F2 /* main.swift */; }; 11 | 84E24F951E8103CB00CBC3F2 /* Heap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E24F941E8103CB00CBC3F2 /* Heap.swift */; }; 12 | /* End PBXBuildFile section */ 13 | 14 | /* Begin PBXCopyFilesBuildPhase section */ 15 | 84E24F881E8102D200CBC3F2 /* CopyFiles */ = { 16 | isa = PBXCopyFilesBuildPhase; 17 | buildActionMask = 2147483647; 18 | dstPath = /usr/share/man/man1/; 19 | dstSubfolderSpec = 0; 20 | files = ( 21 | ); 22 | runOnlyForDeploymentPostprocessing = 1; 23 | }; 24 | /* End PBXCopyFilesBuildPhase section */ 25 | 26 | /* Begin PBXFileReference section */ 27 | 84E24F8A1E8102D200CBC3F2 /* 01-Heap */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "01-Heap"; sourceTree = BUILT_PRODUCTS_DIR; }; 28 | 84E24F8D1E8102D300CBC3F2 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; 29 | 84E24F941E8103CB00CBC3F2 /* Heap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Heap.swift; sourceTree = ""; }; 30 | /* End PBXFileReference section */ 31 | 32 | /* Begin PBXFrameworksBuildPhase section */ 33 | 84E24F871E8102D200CBC3F2 /* Frameworks */ = { 34 | isa = PBXFrameworksBuildPhase; 35 | buildActionMask = 2147483647; 36 | files = ( 37 | ); 38 | runOnlyForDeploymentPostprocessing = 0; 39 | }; 40 | /* End PBXFrameworksBuildPhase section */ 41 | 42 | /* Begin PBXGroup section */ 43 | 84E24F811E8102D200CBC3F2 = { 44 | isa = PBXGroup; 45 | children = ( 46 | 84E24F8C1E8102D200CBC3F2 /* 01-Heap */, 47 | 84E24F8B1E8102D200CBC3F2 /* Products */, 48 | ); 49 | sourceTree = ""; 50 | }; 51 | 84E24F8B1E8102D200CBC3F2 /* Products */ = { 52 | isa = PBXGroup; 53 | children = ( 54 | 84E24F8A1E8102D200CBC3F2 /* 01-Heap */, 55 | ); 56 | name = Products; 57 | sourceTree = ""; 58 | }; 59 | 84E24F8C1E8102D200CBC3F2 /* 01-Heap */ = { 60 | isa = PBXGroup; 61 | children = ( 62 | 84E24F8D1E8102D300CBC3F2 /* main.swift */, 63 | 84E24F941E8103CB00CBC3F2 /* Heap.swift */, 64 | ); 65 | path = "01-Heap"; 66 | sourceTree = ""; 67 | }; 68 | /* End PBXGroup section */ 69 | 70 | /* Begin PBXNativeTarget section */ 71 | 84E24F891E8102D200CBC3F2 /* 01-Heap */ = { 72 | isa = PBXNativeTarget; 73 | buildConfigurationList = 84E24F911E8102D300CBC3F2 /* Build configuration list for PBXNativeTarget "01-Heap" */; 74 | buildPhases = ( 75 | 84E24F861E8102D200CBC3F2 /* Sources */, 76 | 84E24F871E8102D200CBC3F2 /* Frameworks */, 77 | 84E24F881E8102D200CBC3F2 /* CopyFiles */, 78 | ); 79 | buildRules = ( 80 | ); 81 | dependencies = ( 82 | ); 83 | name = "01-Heap"; 84 | productName = "01-Heap"; 85 | productReference = 84E24F8A1E8102D200CBC3F2 /* 01-Heap */; 86 | productType = "com.apple.product-type.tool"; 87 | }; 88 | /* End PBXNativeTarget section */ 89 | 90 | /* Begin PBXProject section */ 91 | 84E24F821E8102D200CBC3F2 /* Project object */ = { 92 | isa = PBXProject; 93 | attributes = { 94 | LastSwiftUpdateCheck = 0820; 95 | LastUpgradeCheck = 0820; 96 | ORGANIZATIONNAME = "买明"; 97 | TargetAttributes = { 98 | 84E24F891E8102D200CBC3F2 = { 99 | CreatedOnToolsVersion = 8.2.1; 100 | DevelopmentTeam = LEG7CXMPKJ; 101 | ProvisioningStyle = Automatic; 102 | }; 103 | }; 104 | }; 105 | buildConfigurationList = 84E24F851E8102D200CBC3F2 /* Build configuration list for PBXProject "01-Heap" */; 106 | compatibilityVersion = "Xcode 3.2"; 107 | developmentRegion = English; 108 | hasScannedForEncodings = 0; 109 | knownRegions = ( 110 | en, 111 | ); 112 | mainGroup = 84E24F811E8102D200CBC3F2; 113 | productRefGroup = 84E24F8B1E8102D200CBC3F2 /* Products */; 114 | projectDirPath = ""; 115 | projectRoot = ""; 116 | targets = ( 117 | 84E24F891E8102D200CBC3F2 /* 01-Heap */, 118 | ); 119 | }; 120 | /* End PBXProject section */ 121 | 122 | /* Begin PBXSourcesBuildPhase section */ 123 | 84E24F861E8102D200CBC3F2 /* Sources */ = { 124 | isa = PBXSourcesBuildPhase; 125 | buildActionMask = 2147483647; 126 | files = ( 127 | 84E24F8E1E8102D300CBC3F2 /* main.swift in Sources */, 128 | 84E24F951E8103CB00CBC3F2 /* Heap.swift in Sources */, 129 | ); 130 | runOnlyForDeploymentPostprocessing = 0; 131 | }; 132 | /* End PBXSourcesBuildPhase section */ 133 | 134 | /* Begin XCBuildConfiguration section */ 135 | 84E24F8F1E8102D300CBC3F2 /* Debug */ = { 136 | isa = XCBuildConfiguration; 137 | buildSettings = { 138 | ALWAYS_SEARCH_USER_PATHS = NO; 139 | CLANG_ANALYZER_NONNULL = YES; 140 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 141 | CLANG_CXX_LIBRARY = "libc++"; 142 | CLANG_ENABLE_MODULES = YES; 143 | CLANG_ENABLE_OBJC_ARC = YES; 144 | CLANG_WARN_BOOL_CONVERSION = YES; 145 | CLANG_WARN_CONSTANT_CONVERSION = YES; 146 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 147 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 148 | CLANG_WARN_EMPTY_BODY = YES; 149 | CLANG_WARN_ENUM_CONVERSION = YES; 150 | CLANG_WARN_INFINITE_RECURSION = YES; 151 | CLANG_WARN_INT_CONVERSION = YES; 152 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 153 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 154 | CLANG_WARN_UNREACHABLE_CODE = YES; 155 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 156 | CODE_SIGN_IDENTITY = "-"; 157 | COPY_PHASE_STRIP = NO; 158 | DEBUG_INFORMATION_FORMAT = dwarf; 159 | ENABLE_STRICT_OBJC_MSGSEND = YES; 160 | ENABLE_TESTABILITY = YES; 161 | GCC_C_LANGUAGE_STANDARD = gnu99; 162 | GCC_DYNAMIC_NO_PIC = NO; 163 | GCC_NO_COMMON_BLOCKS = YES; 164 | GCC_OPTIMIZATION_LEVEL = 0; 165 | GCC_PREPROCESSOR_DEFINITIONS = ( 166 | "DEBUG=1", 167 | "$(inherited)", 168 | ); 169 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 170 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 171 | GCC_WARN_UNDECLARED_SELECTOR = YES; 172 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 173 | GCC_WARN_UNUSED_FUNCTION = YES; 174 | GCC_WARN_UNUSED_VARIABLE = YES; 175 | MACOSX_DEPLOYMENT_TARGET = 10.12; 176 | MTL_ENABLE_DEBUG_INFO = YES; 177 | ONLY_ACTIVE_ARCH = YES; 178 | SDKROOT = macosx; 179 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 180 | }; 181 | name = Debug; 182 | }; 183 | 84E24F901E8102D300CBC3F2 /* Release */ = { 184 | isa = XCBuildConfiguration; 185 | buildSettings = { 186 | ALWAYS_SEARCH_USER_PATHS = NO; 187 | CLANG_ANALYZER_NONNULL = YES; 188 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 189 | CLANG_CXX_LIBRARY = "libc++"; 190 | CLANG_ENABLE_MODULES = YES; 191 | CLANG_ENABLE_OBJC_ARC = YES; 192 | CLANG_WARN_BOOL_CONVERSION = YES; 193 | CLANG_WARN_CONSTANT_CONVERSION = YES; 194 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 195 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 196 | CLANG_WARN_EMPTY_BODY = YES; 197 | CLANG_WARN_ENUM_CONVERSION = YES; 198 | CLANG_WARN_INFINITE_RECURSION = YES; 199 | CLANG_WARN_INT_CONVERSION = YES; 200 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 201 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 202 | CLANG_WARN_UNREACHABLE_CODE = YES; 203 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 204 | CODE_SIGN_IDENTITY = "-"; 205 | COPY_PHASE_STRIP = NO; 206 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 207 | ENABLE_NS_ASSERTIONS = NO; 208 | ENABLE_STRICT_OBJC_MSGSEND = YES; 209 | GCC_C_LANGUAGE_STANDARD = gnu99; 210 | GCC_NO_COMMON_BLOCKS = YES; 211 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 212 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 213 | GCC_WARN_UNDECLARED_SELECTOR = YES; 214 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 215 | GCC_WARN_UNUSED_FUNCTION = YES; 216 | GCC_WARN_UNUSED_VARIABLE = YES; 217 | MACOSX_DEPLOYMENT_TARGET = 10.12; 218 | MTL_ENABLE_DEBUG_INFO = NO; 219 | SDKROOT = macosx; 220 | }; 221 | name = Release; 222 | }; 223 | 84E24F921E8102D300CBC3F2 /* Debug */ = { 224 | isa = XCBuildConfiguration; 225 | buildSettings = { 226 | DEVELOPMENT_TEAM = LEG7CXMPKJ; 227 | PRODUCT_NAME = "$(TARGET_NAME)"; 228 | SWIFT_VERSION = 3.0; 229 | }; 230 | name = Debug; 231 | }; 232 | 84E24F931E8102D300CBC3F2 /* Release */ = { 233 | isa = XCBuildConfiguration; 234 | buildSettings = { 235 | DEVELOPMENT_TEAM = LEG7CXMPKJ; 236 | PRODUCT_NAME = "$(TARGET_NAME)"; 237 | SWIFT_VERSION = 3.0; 238 | }; 239 | name = Release; 240 | }; 241 | /* End XCBuildConfiguration section */ 242 | 243 | /* Begin XCConfigurationList section */ 244 | 84E24F851E8102D200CBC3F2 /* Build configuration list for PBXProject "01-Heap" */ = { 245 | isa = XCConfigurationList; 246 | buildConfigurations = ( 247 | 84E24F8F1E8102D300CBC3F2 /* Debug */, 248 | 84E24F901E8102D300CBC3F2 /* Release */, 249 | ); 250 | defaultConfigurationIsVisible = 0; 251 | defaultConfigurationName = Release; 252 | }; 253 | 84E24F911E8102D300CBC3F2 /* Build configuration list for PBXNativeTarget "01-Heap" */ = { 254 | isa = XCConfigurationList; 255 | buildConfigurations = ( 256 | 84E24F921E8102D300CBC3F2 /* Debug */, 257 | 84E24F931E8102D300CBC3F2 /* Release */, 258 | ); 259 | defaultConfigurationIsVisible = 0; 260 | }; 261 | /* End XCConfigurationList section */ 262 | }; 263 | rootObject = 84E24F821E8102D200CBC3F2 /* Project object */; 264 | } 265 | -------------------------------------------------------------------------------- /DataStructure/01-Heap/01-Heap.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /DataStructure/01-Heap/01-Heap/Heap.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Heap.swift 3 | // 01-Heap 4 | // 5 | // Created by 买明 on 21/03/2017. 6 | // Copyright © 2017 买明. All rights reserved. 7 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 8 | 9 | import Foundation 10 | 11 | public struct Heap: CustomStringConvertible { 12 | 13 | var isOrdered: (T, T) -> Bool 14 | var capacity: Int 15 | 16 | var elements: Array 17 | 18 | var count: Int { 19 | return elements.count 20 | } 21 | var isEmpty: Bool { 22 | return elements.isEmpty 23 | } 24 | 25 | public var description: String { 26 | return elements.description 27 | } 28 | 29 | init(_ capacity: Int, _ isOrdered: @escaping (T, T) -> Bool) { 30 | self.capacity = capacity 31 | self.isOrdered = isOrdered 32 | self.elements = Array() 33 | } 34 | 35 | private mutating func shiftUp(_ index: Int) { 36 | var index = index 37 | while index > 0 && isOrdered(elements[index], elements[(index - 1) / 2]) { 38 | swap(&elements[index], &elements[(index - 1) / 2]) 39 | index = (index - 1) / 2 40 | } 41 | } 42 | 43 | private mutating func shiftDown(_ index: Int) { 44 | var index = index 45 | while 2 * (index + 1) <= count { 46 | var j = 2 * index + 1 47 | if j + 1 < count && isOrdered(elements[j + 1], elements[j]) { 48 | j += 1 49 | } 50 | 51 | if isOrdered(elements[j], elements[index]) { 52 | swap(&elements[j], &elements[index]) 53 | } 54 | index = j 55 | } 56 | } 57 | 58 | mutating func insert(_ element: T) { 59 | assert(count + 1 <= capacity, "Heap out of capacity.") 60 | elements.append(element) 61 | shiftUp(count - 1) 62 | } 63 | 64 | mutating func extractExtremum() -> T { 65 | assert(!isEmpty, "Heap is Empty") 66 | let returnElement = elements[0] 67 | if count > 1 { 68 | swap(&elements[0], &elements[count - 1]) 69 | } 70 | elements.removeLast() 71 | shiftDown(0) 72 | return returnElement 73 | } 74 | 75 | public func getExtremum() -> T { 76 | assert(!isEmpty, "Heap is Empty") 77 | return elements[0] 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /DataStructure/01-Heap/01-Heap/main.swift: -------------------------------------------------------------------------------- 1 | // 2 | // main.swift 3 | // 01-Heap 4 | // 5 | // Created by 买明 on 21/03/2017. 6 | // Copyright © 2017 买明. All rights reserved. 7 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 8 | 9 | import Foundation 10 | 11 | // Build a Max Heap with Int vars & 100 capacity 12 | var myMaxHeap = Heap(100, >) 13 | 14 | // Test insert(:) func. 15 | myMaxHeap.insert(1) 16 | myMaxHeap.insert(2) 17 | myMaxHeap.insert(3) 18 | myMaxHeap.insert(4) 19 | myMaxHeap.insert(5) 20 | 21 | print(myMaxHeap) 22 | 23 | // Test extractExtremum() func. 24 | print(myMaxHeap.extractExtremum()) 25 | print(myMaxHeap) 26 | 27 | print(myMaxHeap.extractExtremum()) 28 | print(myMaxHeap) 29 | 30 | print(myMaxHeap.extractExtremum()) 31 | print(myMaxHeap) 32 | -------------------------------------------------------------------------------- /DataStructure/01-Heap/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | public struct Heap: CustomStringConvertible { 9 | 10 | var isOrdered: (T, T) -> Bool 11 | var capacity: Int 12 | 13 | var elements: Array 14 | 15 | var count: Int { 16 | return elements.count 17 | } 18 | var isEmpty: Bool { 19 | return elements.isEmpty 20 | } 21 | 22 | public var description: String { 23 | return elements.description 24 | } 25 | 26 | init(_ capacity: Int, _ isOrdered: @escaping (T, T) -> Bool) { 27 | self.capacity = capacity 28 | self.isOrdered = isOrdered 29 | self.elements = Array() 30 | } 31 | 32 | private mutating func shiftUp(_ index: Int) { 33 | var index = index 34 | while index > 0 && isOrdered(elements[index], elements[(index - 1) / 2]) { 35 | swap(&elements[index], &elements[(index - 1) / 2]) 36 | index = (index - 1) / 2 37 | } 38 | } 39 | 40 | private mutating func shiftDown(_ index: Int) { 41 | var index = index 42 | while 2 * (index + 1) <= count { 43 | var j = 2 * index + 1 44 | if j + 1 < count && isOrdered(elements[j + 1], elements[j]) { 45 | j += 1 46 | } 47 | 48 | if isOrdered(elements[j], elements[index]) { 49 | swap(&elements[j], &elements[index]) 50 | } 51 | index = j 52 | } 53 | } 54 | 55 | mutating func insert(_ element: T) { 56 | assert(count + 1 <= capacity, "Heap out of capacity.") 57 | elements.append(element) 58 | shiftUp(count - 1) 59 | } 60 | 61 | mutating func extractExtremum() -> T { 62 | assert(!isEmpty, "Heap is Empty") 63 | let returnElement = elements[0] 64 | if count > 1 { 65 | swap(&elements[0], &elements[count - 1]) 66 | } 67 | elements.removeLast() 68 | shiftDown(0) 69 | return returnElement 70 | } 71 | 72 | public func getExtremum() -> T { 73 | assert(!isEmpty, "Heap is Empty") 74 | return elements[0] 75 | } 76 | 77 | } 78 | ``` 79 | 80 | ## License 81 | 82 | MIT 83 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 萌面大道 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LeetCode/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Launch file", 9 | "type": "go", 10 | "request": "launch", 11 | "mode": "auto", 12 | "program": "${file}" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /LeetCode/001-Two-Sum/001-Two-Sum.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution_1 { 4 | // 688 ms 5 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 6 | for i in 0.. [Int] { 20 | var dict = [Int : Int]() 21 | 22 | for i in 0.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/001-Two-Sum/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 001 Two Sum 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 688 ms 14 | func twoSum(_ nums: [Int], _ target: Int) -> [Int] { 15 | for i in 0.. [Int] { 29 | var dict = [Int : Int]() 30 | 31 | for i in 0.. Int { 6 | var x = x 7 | var result = 0 8 | 9 | while x != 0 { 10 | result *= 10 11 | result += x % 10 12 | x /= 10 13 | } 14 | 15 | guard result <= Int32.max && result >= Int32.min else { return 0 } 16 | 17 | return result 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/007-Reverse-Integer/007-Reverse-Integer.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/007-Reverse-Integer/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 007 Reverse Integer 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 12 ms 14 | func reverse(_ x: Int) -> Int { 15 | var x = x 16 | var result = 0 17 | 18 | while x != 0 { 19 | result *= 10 20 | result += x % 10 21 | x /= 10 22 | } 23 | 24 | guard result <= Int32.max && result >= Int32.min else { return 0 } 25 | 26 | return result 27 | } 28 | } 29 | ``` 30 | 31 | #### Go 32 | 33 | ```go 34 | func reverse(x int) int { 35 | 36 | } 37 | ``` 38 | 39 | #### Python 40 | 41 | ```python 42 | class Solution: 43 | def reverse(self, x): 44 | """ 45 | :type x: int 46 | :rtype: int 47 | """ 48 | 49 | ``` 50 | 51 | ## License 52 | 53 | - MIT 54 | -------------------------------------------------------------------------------- /LeetCode/009-Palindrome-Number/009-Palindrome-Number.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution_1 { 4 | // 80 ms 5 | func isPalindrome(_ x: Int) -> Bool { 6 | var x = x 7 | guard x >= 0 else { return false } 8 | 9 | var digits = [Int]() 10 | while x != 0 { 11 | digits.append(x % 10) 12 | x /= 10 13 | } 14 | 15 | return digits == digits.reversed() 16 | } 17 | } 18 | 19 | class Solution_2 { 20 | // 56 ms 21 | func isPalindrome(_ x: Int) -> Bool { 22 | var y = x 23 | guard x >= 0 else { return false } 24 | 25 | var result = 0 26 | while y != 0 { 27 | result *= 10 28 | result += y % 10 29 | y /= 10 30 | } 31 | 32 | return result == x 33 | } 34 | } 35 | 36 | class Solution_3 { 37 | // 56 ms 38 | func isPalindrome(_ x: Int) -> Bool { 39 | var x = x 40 | guard x >= 0, 41 | x % 10 != 0 || x == 0 else { return false } 42 | 43 | var result = 0 44 | while x > result { 45 | result = result * 10 + x % 10 46 | x /= 10 47 | } 48 | 49 | return result == x || result / 10 == x 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /LeetCode/009-Palindrome-Number/009-Palindrome-Number.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/009-Palindrome-Number/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 009 Palindrome Number 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | 13 | class Solution_1 { 14 | // 80 ms 15 | func isPalindrome(_ x: Int) -> Bool { 16 | var x = x 17 | guard x >= 0 else { return false } 18 | 19 | var digits = [Int]() 20 | while x != 0 { 21 | digits.append(x % 10) 22 | x /= 10 23 | } 24 | 25 | return digits == digits.reversed() 26 | } 27 | } 28 | 29 | class Solution_2 { 30 | // 56 ms 31 | func isPalindrome(_ x: Int) -> Bool { 32 | var y = x 33 | guard x >= 0 else { return false } 34 | 35 | var result = 0 36 | while y != 0 { 37 | result *= 10 38 | result += y % 10 39 | y /= 10 40 | } 41 | 42 | return result == x 43 | } 44 | } 45 | 46 | class Solution_3 { 47 | // 56 ms 48 | func isPalindrome(_ x: Int) -> Bool { 49 | var x = x 50 | guard x >= 0, 51 | x % 10 != 0 || x == 0 else { return false } 52 | 53 | var result = 0 54 | while x > result { 55 | result = result * 10 + x % 10 56 | x /= 10 57 | } 58 | 59 | return result == x || result / 10 == x 60 | } 61 | } 62 | ``` 63 | 64 | #### Go 65 | 66 | ```go 67 | func isPalindrome(x int) bool { 68 | 69 | } 70 | ``` 71 | 72 | #### Python 73 | 74 | ```python 75 | class Solution: 76 | def isPalindrome(self, x): 77 | """ 78 | :type x: int 79 | :rtype: bool 80 | """ 81 | 82 | ``` 83 | 84 | ## License 85 | 86 | - MIT 87 | -------------------------------------------------------------------------------- /LeetCode/013-Roman-to-Integer/013-Roman-to-Integer.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 52 ms 5 | func romanToInt(_ s: String) -> Int { 6 | let dict = ["I" : 1, 7 | "V" : 5, 8 | "X" : 10, 9 | "L" : 50, 10 | "C" : 100, 11 | "D" : 500, 12 | "M" : 1000] 13 | guard !s.isEmpty else { fatalError("s is empty.") } 14 | guard let last = s.last, 15 | var result = dict[String(last)] else { fatalError("Unknown error.") } 16 | 17 | for i in 1.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/013-Roman-to-Integer/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 013 Roman to Integer 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 52 ms 14 | func romanToInt(_ s: String) -> Int { 15 | let dict = ["I" : 1, 16 | "V" : 5, 17 | "X" : 10, 18 | "L" : 50, 19 | "C" : 100, 20 | "D" : 500, 21 | "M" : 1000] 22 | guard !s.isEmpty else { fatalError("s is empty.") } 23 | guard let last = s.last, 24 | var result = dict[String(last)] else { fatalError("Unknown error.") } 25 | 26 | for i in 1.. String { 6 | guard !strs.isEmpty, 7 | let firstStr = strs.first else { return "" } 8 | guard strs.count > 1 || firstStr.count > 1 else { return firstStr } 9 | 10 | var commonPrefix = "" 11 | for i in 0.. String { 25 | guard !strs.isEmpty, 26 | var result = strs.first else { return "" } 27 | 28 | for str in strs.dropFirst() { 29 | while !str.starts(with: result) { 30 | result.removeLast() 31 | } 32 | } 33 | 34 | return result 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LeetCode/014-Longest-Common-Prefix/014-Longest-Common-Prefix.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/014-Longest-Common-Prefix/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 014 Longest Common Prefix 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 304 ms 14 | func longestCommonPrefix(_ strs: [String]) -> String { 15 | guard !strs.isEmpty, 16 | let firstStr = strs.first else { return "" } 17 | guard strs.count > 1 || firstStr.count > 1 else { return firstStr } 18 | 19 | var commonPrefix = "" 20 | for i in 0.. String { 34 | guard !strs.isEmpty, 35 | var result = strs.first else { return "" } 36 | 37 | for str in strs.dropFirst() { 38 | while !str.starts(with: result) { 39 | result.removeLast() 40 | } 41 | } 42 | 43 | return result 44 | } 45 | } 46 | ``` 47 | 48 | #### Go 49 | 50 | ```go 51 | ``` 52 | 53 | #### Python 54 | 55 | ```python 56 | ``` 57 | 58 | ## License 59 | 60 | - MIT 61 | -------------------------------------------------------------------------------- /LeetCode/02.03-delete-middle-node-lcci/delete-middle-node-lcci.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * type ListNode struct { 6 | * Val int 7 | * Next *ListNode 8 | * } 9 | */ 10 | 11 | // ListNode Structure 12 | type ListNode struct { 13 | Val int 14 | Next *ListNode 15 | } 16 | 17 | func deleteNode(node *ListNode) { 18 | // 仅知道当前节点,欲删除当前节点 19 | // 思路:由于删除涉及前驱节点,但单链表无法溯源,因此将 20 | // Next 节点数据复制到当前节点,并删除原有的 Next 节点 21 | node.Val = node.Next.Val 22 | node.Next = node.Next.Next 23 | } 24 | -------------------------------------------------------------------------------- /LeetCode/020-Valid-Parentheses/020-Valid-Parentheses.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 16 ms 5 | func isValid(_ s: String) -> Bool { 6 | guard !s.isEmpty else { return true } 7 | 8 | let dict: [Character : Character] = [ 9 | ")" : "(", 10 | "]" : "[", 11 | "}" : "{" 12 | ] 13 | let openedBrackets: [Character] = ["(", "[", "{"] 14 | let closedBrackets: [Character] = [")", "]", "}"] 15 | 16 | var stack = [Character]() 17 | for c in [Character](s) { 18 | if openedBrackets.contains(c) { 19 | stack.append(c) 20 | } 21 | if closedBrackets.contains(c) { 22 | if let last = stack.popLast(), last == dict[c] { 23 | continue 24 | } else { 25 | return false 26 | } 27 | } 28 | } 29 | 30 | return stack.isEmpty 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LeetCode/020-Valid-Parentheses/020-Valid-Parentheses.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/020-Valid-Parentheses/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 020 Valid Parentheses 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 16 ms 14 | func isValid(_ s: String) -> Bool { 15 | guard !s.isEmpty else { return true } 16 | 17 | let dict: [Character : Character] = [ 18 | ")" : "(", 19 | "]" : "[", 20 | "}" : "{" 21 | ] 22 | let openedBrackets: [Character] = ["(", "[", "{"] 23 | let closedBrackets: [Character] = [")", "]", "}"] 24 | 25 | var stack = [Character]() 26 | for c in [Character](s) { 27 | if openedBrackets.contains(c) { 28 | stack.append(c) 29 | } 30 | if closedBrackets.contains(c) { 31 | if let last = stack.popLast(), last == dict[c] { 32 | continue 33 | } else { 34 | return false 35 | } 36 | } 37 | } 38 | 39 | return stack.isEmpty 40 | } 41 | } 42 | ``` 43 | 44 | #### Go 45 | 46 | ```go 47 | ``` 48 | 49 | #### Python 50 | 51 | ```python 52 | ``` 53 | 54 | ## License 55 | 56 | - MIT 57 | -------------------------------------------------------------------------------- /LeetCode/021-Merge-Two-Sorted-Lists/021-Merge-Two-Sorted-Lists.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | public class ListNode { 4 | public var val: Int 5 | public var next: ListNode? 6 | public init(_ val: Int) { 7 | self.val = val 8 | self.next = nil 9 | } 10 | } 11 | 12 | class Solution_1 { 13 | // 20 ms 14 | func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { 15 | guard let l1 = l1 else { return l2 } 16 | guard let l2 = l2 else { return l1 } 17 | 18 | if l1.val < l2.val { 19 | l1.next = mergeTwoLists(l1.next, l2) 20 | return l1 21 | } else { 22 | l2.next = mergeTwoLists(l1, l2.next) 23 | return l2 24 | } 25 | } 26 | } 27 | 28 | class Solution_2 { 29 | // 20 ms 30 | func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { 31 | var l1 = l1, l2 = l2 32 | 33 | let head = ListNode(0) 34 | var current = head 35 | 36 | while let val1 = l1?.val, let val2 = l2?.val { 37 | if val1 > val2 { 38 | current.next = l2 39 | l2 = l2?.next 40 | } else { 41 | current.next = l1 42 | l1 = l1?.next 43 | } 44 | current = current.next! 45 | } 46 | if l1 == nil { 47 | current.next = l2 48 | } else { 49 | current.next = l1 50 | } 51 | 52 | return head.next 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /LeetCode/021-Merge-Two-Sorted-Lists/021-Merge-Two-Sorted-Lists.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/021-Merge-Two-Sorted-Lists/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 021 Merge Two Sorted Lists 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | public class ListNode { 13 | public var val: Int 14 | public var next: ListNode? 15 | public init(_ val: Int) { 16 | self.val = val 17 | self.next = nil 18 | } 19 | } 20 | 21 | class Solution_1 { 22 | // 20 ms 23 | func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { 24 | guard let l1 = l1 else { return l2 } 25 | guard let l2 = l2 else { return l1 } 26 | 27 | if l1.val < l2.val { 28 | l1.next = mergeTwoLists(l1.next, l2) 29 | return l1 30 | } else { 31 | l2.next = mergeTwoLists(l1, l2.next) 32 | return l2 33 | } 34 | } 35 | } 36 | 37 | class Solution_2 { 38 | // 20 ms 39 | func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { 40 | var l1 = l1, l2 = l2 41 | 42 | let head = ListNode(0) 43 | var current = head 44 | 45 | while let val1 = l1?.val, let val2 = l2?.val { 46 | if val1 > val2 { 47 | current.next = l2 48 | l2 = l2?.next 49 | } else { 50 | current.next = l1 51 | l1 = l1?.next 52 | } 53 | current = current.next! 54 | } 55 | if l1 == nil { 56 | current.next = l2 57 | } else { 58 | current.next = l1 59 | } 60 | 61 | return head.next 62 | } 63 | } 64 | ``` 65 | 66 | #### Go 67 | 68 | ```go 69 | ``` 70 | 71 | #### Python 72 | 73 | ```python 74 | ``` 75 | 76 | ## License 77 | 78 | - MIT 79 | -------------------------------------------------------------------------------- /LeetCode/026-Remove-Duplicates-from-Sorted-Array/026-Remove-Duplicates-from-Sorted-Array.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution_1 { 4 | // 92 ms 5 | func removeDuplicates(_ nums: inout [Int]) -> Int { 6 | nums = Array(Set(nums)).sorted() 7 | return nums.count 8 | } 9 | } 10 | 11 | class Solution_2 { 12 | // 84 ms 13 | func removeDuplicates(_ nums: inout [Int]) -> Int { 14 | guard !nums.isEmpty else { return 0 } 15 | 16 | var i = 0 17 | for j in 1.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/026-Remove-Duplicates-from-Sorted-Array/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 026 Remove Duplicates from Sorted Array 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 92 ms 14 | func removeDuplicates(_ nums: inout [Int]) -> Int { 15 | nums = Array(Set(nums)).sorted() 16 | return nums.count 17 | } 18 | } 19 | 20 | class Solution_2 { 21 | // 84 ms 22 | func removeDuplicates(_ nums: inout [Int]) -> Int { 23 | guard !nums.isEmpty else { return 0 } 24 | 25 | var i = 0 26 | for j in 1.. Int { 6 | nums = nums.filter { $0 != val } 7 | return nums.count 8 | } 9 | } 10 | 11 | class Solution { 12 | // 12 ms 13 | func removeElement(_ nums: inout [Int], _ val: Int) -> Int { 14 | var i = 0 15 | for j in 0.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/027-Remove-Element/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 027 Remove Element 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 12 ms 14 | func removeElement(_ nums: inout [Int], _ val: Int) -> Int { 15 | nums = nums.filter { $0 != val } 16 | return nums.count 17 | } 18 | } 19 | 20 | class Solution { 21 | // 12 ms 22 | func removeElement(_ nums: inout [Int], _ val: Int) -> Int { 23 | var i = 0 24 | for j in 0.. Int { 6 | guard !needle.isEmpty else { return 0 } 7 | guard haystack.count >= needle.count else { return -1 } 8 | 9 | let distance = haystack.count - needle.count 10 | for i in 0...distance { 11 | let start = haystack.index(haystack.startIndex, offsetBy: i) 12 | let end = haystack.index(haystack.startIndex, offsetBy: i+needle.count) 13 | 14 | if haystack[start.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/028-Implement-strStr()/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 028 Implement strStr() 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 20 ms 14 | func strStr(_ haystack: String, _ needle: String) -> Int { 15 | guard !needle.isEmpty else { return 0 } 16 | guard haystack.count >= needle.count else { return -1 } 17 | 18 | let distance = haystack.count - needle.count 19 | for i in 0...distance { 20 | let start = haystack.index(haystack.startIndex, offsetBy: i) 21 | let end = haystack.index(haystack.startIndex, offsetBy: i+needle.count) 22 | 23 | if haystack[start.. Int { 6 | if let index = nums.firstIndex(of: target) { 7 | return index 8 | } 9 | var nums = nums 10 | 11 | nums.append(target) 12 | return nums.sorted().firstIndex(of: target) ?? 0 13 | } 14 | } 15 | 16 | class Solution_2 { 17 | // 40 ms 18 | func searchInsert(_ nums: [Int], _ target: Int) -> Int { 19 | if let last = nums.last, last < target { 20 | return nums.count 21 | } 22 | for i in 0..= nums[i] && target <= nums[i+1] { 27 | return i + 1 28 | } 29 | } 30 | return 0 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LeetCode/035-Search-Insert-Position/035-Search-Insert-Position.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/035-Search-Insert-Position/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 035 Search Insert Position 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 44 ms 14 | func searchInsert(_ nums: [Int], _ target: Int) -> Int { 15 | if let index = nums.firstIndex(of: target) { 16 | return index 17 | } 18 | var nums = nums 19 | 20 | nums.append(target) 21 | return nums.sorted().firstIndex(of: target) ?? 0 22 | } 23 | } 24 | 25 | class Solution_2 { 26 | // 40 ms 27 | func searchInsert(_ nums: [Int], _ target: Int) -> Int { 28 | if let last = nums.last, last < target { 29 | return nums.count 30 | } 31 | for i in 0..= nums[i] && target <= nums[i+1] { 36 | return i + 1 37 | } 38 | } 39 | return 0 40 | } 41 | } 42 | ``` 43 | 44 | #### Go 45 | 46 | ```go 47 | ``` 48 | 49 | #### Python 50 | 51 | ```python 52 | ``` 53 | 54 | ## License 55 | 56 | - MIT 57 | -------------------------------------------------------------------------------- /LeetCode/038-Count-and-Say/038-Count-and-Say.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 24 ms 5 | func countAndSay(_ n: Int) -> String { 6 | guard n >= 1 && n <= 30 else { fatalError("n is out of range.") } 7 | 8 | var result = "1" 9 | for _ in 1.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/038-Count-and-Say/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 038 Count and Say 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 24 ms 14 | func countAndSay(_ n: Int) -> String { 15 | guard n >= 1 && n <= 30 else { fatalError("n is out of range.") } 16 | 17 | var result = "1" 18 | for _ in 1.. Int { 6 | guard nums.count > 1 else { return nums.first ?? 0 } 7 | 8 | var theMax = nums[0] 9 | var currentMax = nums[0] 10 | for i in 1.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/053-Maximum-Subarray/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 053 Maximum Subarray 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 44 ms 14 | func maxSubArray(_ nums: [Int]) -> Int { 15 | guard nums.count > 1 else { return nums.first ?? 0 } 16 | 17 | var theMax = nums[0] 18 | var currentMax = nums[0] 19 | for i in 1.. [Int] { 6 | guard !matrix.isEmpty else { return [] } 7 | guard !matrix[0].isEmpty else { return [] } 8 | guard startX >= 0 && startY >= 0 && m > 0 && n > 0 else { 9 | return [] 10 | } 11 | 12 | var result = matrix[startX][startY.. 1 { 15 | result.append(contentsOf: (startX+1.. 1 && n > 1 { 19 | result.append(contentsOf: (startY+1.. 1 { 23 | result.append(contentsOf: (startX+1.. [Int] { 32 | guard !matrix.isEmpty else { return [] } 33 | guard !matrix[0].isEmpty else { return [] } 34 | return externalElements(matrix, 0, 0, matrix[0].count, matrix.count) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /LeetCode/054-Spiral-Matrix/054-Spiral-Matrix.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/054-Spiral-Matrix/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 054 Spiral Matrix 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```swift 12 | class Solution { 13 | // 4 ms 14 | func externalElements(_ matrix: [[Int]], _ startX: Int, _ startY: Int, _ m: Int, _ n: Int) -> [Int] { 15 | guard !matrix.isEmpty else { return [] } 16 | guard !matrix[0].isEmpty else { return [] } 17 | guard startX >= 0 && startY >= 0 && m > 0 && n > 0 else { 18 | return [] 19 | } 20 | 21 | var result = matrix[startX][startY.. 1 { 24 | result.append(contentsOf: (startX+1.. 1 && n > 1 { 28 | result.append(contentsOf: (startY+1.. 1 { 32 | result.append(contentsOf: (startX+1.. [Int] { 41 | guard !matrix.isEmpty else { return [] } 42 | guard !matrix[0].isEmpty else { return [] } 43 | return externalElements(matrix, 0, 0, matrix[0].count, matrix.count) 44 | } 45 | } 46 | ``` 47 | 48 | #### Go 49 | 50 | ```go 51 | ``` 52 | 53 | #### Python 54 | 55 | ```python 56 | ``` 57 | 58 | ## License 59 | 60 | - MIT 61 | -------------------------------------------------------------------------------- /LeetCode/058-Length-of-Last-Word/058-Length-of-Last-Word.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 16 ms 5 | func lengthOfLastWord(_ s: String) -> Int { 6 | let s = s.trimmingCharacters(in: CharacterSet(charactersIn: " ")) 7 | guard let index = s.lastIndex(of: " ") else { return s.count } 8 | return s[index...].count - 1 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /LeetCode/058-Length-of-Last-Word/058-Length-of-Last-Word.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/058-Length-of-Last-Word/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 058 Length of Last Word 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 16 ms 14 | func lengthOfLastWord(_ s: String) -> Int { 15 | let s = s.trimmingCharacters(in: CharacterSet(charactersIn: " ")) 16 | guard let index = s.lastIndex(of: " ") else { return s.count } 17 | return s[index...].count - 1 18 | } 19 | } 20 | ``` 21 | 22 | #### Go 23 | 24 | ```go 25 | ``` 26 | 27 | #### Python 28 | 29 | ```python 30 | ``` 31 | 32 | ## License 33 | 34 | - MIT 35 | -------------------------------------------------------------------------------- /LeetCode/066-Plus-One/066-Plus-One.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution_1 { 4 | // 12 ms 5 | func plusOne(_ digits: [Int]) -> [Int] { 6 | guard let last = digits.last else { fatalError("digits is empty.") } 7 | var digits = digits 8 | 9 | if last == 9 { 10 | digits[digits.count-1] = 10 11 | for i in 1...digits.count { 12 | if digits[digits.count-i] > 9 { 13 | digits[digits.count-i] = 0 14 | if digits.count - i - 1 >= 0 { 15 | digits[digits.count-i-1] += 1 16 | } else { 17 | digits.insert(1, at: 0) 18 | } 19 | } else { 20 | if i == 1 { 21 | digits[digits.count-i] += 1 22 | } 23 | break 24 | } 25 | } 26 | } else { 27 | digits[digits.count-1] += 1 28 | } 29 | return digits 30 | } 31 | } 32 | 33 | class Solution_2 { 34 | // 8 ms 35 | func plusOne(_ digits: [Int]) -> [Int] { 36 | guard !digits.isEmpty else { return [] } 37 | 38 | var digits = digits 39 | 40 | digits[digits.count - 1] += 1 41 | for t in digits.enumerated().reversed() { 42 | if digits[t.offset] == 10 { 43 | digits[t.offset] = 0 44 | if t.offset == 0 { 45 | digits.insert(1, at: 0) 46 | } else { 47 | digits[t.offset - 1] += 1 48 | } 49 | } 50 | } 51 | 52 | return digits 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /LeetCode/066-Plus-One/066-Plus-One.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/066-Plus-One/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 066 Plus One 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 12 ms 14 | func plusOne(_ digits: [Int]) -> [Int] { 15 | guard let last = digits.last else { fatalError("digits is empty.") } 16 | var digits = digits 17 | 18 | if last == 9 { 19 | digits[digits.count-1] = 10 20 | for i in 1...digits.count { 21 | if digits[digits.count-i] > 9 { 22 | digits[digits.count-i] = 0 23 | if digits.count - i - 1 >= 0 { 24 | digits[digits.count-i-1] += 1 25 | } else { 26 | digits.insert(1, at: 0) 27 | } 28 | } else { 29 | if i == 1 { 30 | digits[digits.count-i] += 1 31 | } 32 | break 33 | } 34 | } 35 | } else { 36 | digits[digits.count-1] += 1 37 | } 38 | return digits 39 | } 40 | } 41 | 42 | class Solution_2 { 43 | // 8 ms 44 | func plusOne(_ digits: [Int]) -> [Int] { 45 | guard !digits.isEmpty else { return [] } 46 | 47 | var digits = digits 48 | 49 | digits[digits.count - 1] += 1 50 | for t in digits.enumerated().reversed() { 51 | if digits[t.offset] == 10 { 52 | digits[t.offset] = 0 53 | if t.offset == 0 { 54 | digits.insert(1, at: 0) 55 | } else { 56 | digits[t.offset - 1] += 1 57 | } 58 | } 59 | } 60 | 61 | return digits 62 | } 63 | } 64 | ``` 65 | 66 | #### Go 67 | 68 | ```go 69 | ``` 70 | 71 | #### Python 72 | 73 | ```python 74 | ``` 75 | 76 | ## License 77 | 78 | - MIT 79 | -------------------------------------------------------------------------------- /LeetCode/067-Add-Binary/067-Add-Binary.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution_1 { 4 | // 92 ms 5 | func addBinary(_ a: String, _ b: String) -> String { 6 | let aCount = a.filter { String($0) == "0" || String($0) == "1" }.count 7 | let bCount = b.filter { String($0) == "0" || String($0) == "1" }.count 8 | guard aCount == a.count && bCount == b.count else { fatalError("a or b is not a binary.") } 9 | var a = a, b = b 10 | while a.count != b.count { 11 | if a.count > b.count { 12 | b.insert("0", at: b.startIndex) 13 | } else { 14 | a.insert("0", at: a.startIndex) 15 | } 16 | } 17 | 18 | a.insert("0", at: a.startIndex) 19 | b.insert("0", at: b.startIndex) 20 | 21 | var result = "" 22 | for i in 0..= 2 { 28 | a.replaceSubrange(a.index(a.startIndex, offsetBy: a.count-i-2).. String { 43 | guard a.count >= b.count else { return addBinary(b, a) } 44 | var a = [Character](a).map { Int(String($0))! } 45 | var b = [Character](b).map { Int(String($0))! } 46 | 47 | var temp = 0 48 | var sum = 0 49 | for i in 1...a.count { 50 | if i > b.count { 51 | b.insert(0, at: 0) 52 | } 53 | sum = a[a.count-i] + b[b.count-i] + temp 54 | a[a.count-i] = sum % 2 55 | temp = sum / 2 56 | } 57 | if temp != 0 { 58 | a.insert(temp, at: 0) 59 | } 60 | return String(a.map { Character("\($0)") }) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /LeetCode/067-Add-Binary/067-Add-Binary.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/067-Add-Binary/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 067 Add Binary 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 92 ms 14 | func addBinary(_ a: String, _ b: String) -> String { 15 | let aCount = a.filter { String($0) == "0" || String($0) == "1" }.count 16 | let bCount = b.filter { String($0) == "0" || String($0) == "1" }.count 17 | guard aCount == a.count && bCount == b.count else { fatalError("a or b is not a binary.") } 18 | var a = a, b = b 19 | while a.count != b.count { 20 | if a.count > b.count { 21 | b.insert("0", at: b.startIndex) 22 | } else { 23 | a.insert("0", at: a.startIndex) 24 | } 25 | } 26 | 27 | a.insert("0", at: a.startIndex) 28 | b.insert("0", at: b.startIndex) 29 | 30 | var result = "" 31 | for i in 0..= 2 { 37 | a.replaceSubrange(a.index(a.startIndex, offsetBy: a.count-i-2).. String { 52 | guard a.count >= b.count else { return addBinary(b, a) } 53 | var a = [Character](a).map { Int(String($0))! } 54 | var b = [Character](b).map { Int(String($0))! } 55 | 56 | var temp = 0 57 | var sum = 0 58 | for i in 1...a.count { 59 | if i > b.count { 60 | b.insert(0, at: 0) 61 | } 62 | sum = a[a.count-i] + b[b.count-i] + temp 63 | a[a.count-i] = sum % 2 64 | temp = sum / 2 65 | } 66 | if temp != 0 { 67 | a.insert(temp, at: 0) 68 | } 69 | return String(a.map { Character("\($0)") }) 70 | } 71 | } 72 | ``` 73 | 74 | #### Go 75 | 76 | ```go 77 | ``` 78 | 79 | #### Python 80 | 81 | ```python 82 | ``` 83 | 84 | ## License 85 | 86 | - MIT 87 | -------------------------------------------------------------------------------- /LeetCode/069-Sqrt(x)/069-Sqrt(x).playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution_1 { 4 | // 208 ms 5 | func mySqrt(_ x: Int) -> Int { 6 | guard x > 1 else { return x } 7 | for i in 0...x/2 { 8 | if i * i > x { 9 | return i - 1 10 | } 11 | } 12 | return x/2 13 | } 14 | } 15 | 16 | class Solution_2 { 17 | // 12 ms 18 | func mySqrt(_ x: Int) -> Int { 19 | return Int(sqrt(Double(x))) 20 | } 21 | } 22 | 23 | class Solution_3 { 24 | // 12 ms 25 | func mySqrt(_ x: Int) -> Int { 26 | guard x >= 0 else { fatalError("x is meaningless.") } 27 | guard x > 1 else { return x } 28 | 29 | var low = 2 30 | var high = x / 2 31 | 32 | while low <= high { 33 | let mid = (high + low) / 2 34 | if x / mid > mid { 35 | low = mid + 1 36 | } else if x / mid == mid { 37 | return mid 38 | } else if x / mid < mid { 39 | high = mid - 1 40 | } 41 | } 42 | 43 | return high 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /LeetCode/069-Sqrt(x)/069-Sqrt(x).playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/069-Sqrt(x)/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 069 Sqrt(x) 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 208 ms 14 | func mySqrt(_ x: Int) -> Int { 15 | guard x > 1 else { return x } 16 | for i in 0...x/2 { 17 | if i * i > x { 18 | return i - 1 19 | } 20 | } 21 | return x/2 22 | } 23 | } 24 | 25 | class Solution_2 { 26 | // 12 ms 27 | func mySqrt(_ x: Int) -> Int { 28 | return Int(sqrt(Double(x))) 29 | } 30 | } 31 | 32 | class Solution_3 { 33 | // 12 ms 34 | func mySqrt(_ x: Int) -> Int { 35 | guard x >= 0 else { fatalError("x is meaningless.") } 36 | guard x > 1 else { return x } 37 | 38 | var low = 2 39 | var high = x / 2 40 | 41 | while low <= high { 42 | let mid = (high + low) / 2 43 | if x / mid > mid { 44 | low = mid + 1 45 | } else if x / mid == mid { 46 | return mid 47 | } else if x / mid < mid { 48 | high = mid - 1 49 | } 50 | } 51 | 52 | return high 53 | } 54 | } 55 | ``` 56 | 57 | #### Go 58 | 59 | ```go 60 | ``` 61 | 62 | #### Python 63 | 64 | ```python 65 | ``` 66 | 67 | ## License 68 | 69 | - MIT 70 | -------------------------------------------------------------------------------- /LeetCode/070-Climbing-Stairs/070-Climbing-Stairs.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 12 ms 5 | func climbStairs(_ n: Int) -> Int { 6 | guard n > 2 else { return n } 7 | var steps = [1, 2] 8 | for i in 2.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/070-Climbing-Stairs/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 070 Climbing Stairs 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 12 ms 14 | func climbStairs(_ n: Int) -> Int { 15 | guard n > 2 else { return n } 16 | var steps = [1, 2] 17 | for i in 2.. ListNode? { 26 | var head = head 27 | let node = ListNode(0) 28 | node.next = head 29 | 30 | while head?.next != nil { 31 | var temp = head 32 | temp = temp?.next 33 | if temp?.val == head?.val { 34 | if temp?.next != nil { 35 | head?.next = temp?.next 36 | } else { 37 | head?.next = nil 38 | } 39 | } else { 40 | head = head?.next 41 | } 42 | } 43 | return node.next 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /LeetCode/083-Remove-Duplicates-from-Sorted-List/083-Remove-Duplicates-from-Sorted-List.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/083-Remove-Duplicates-from-Sorted-List/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 083 Remove Duplicates from Sorted List 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 40 ms 14 | func deleteDuplicates(_ head: ListNode?) -> ListNode? { 15 | var head = head 16 | let node = ListNode(0) 17 | node.next = head 18 | 19 | while head?.next != nil { 20 | var temp = head 21 | temp = temp?.next 22 | if temp?.val == head?.val { 23 | if temp?.next != nil { 24 | head?.next = temp?.next 25 | } else { 26 | head?.next = nil 27 | } 28 | } else { 29 | head = head?.next 30 | } 31 | } 32 | return node.next 33 | } 34 | } 35 | ``` 36 | 37 | #### Go 38 | 39 | ```go 40 | ``` 41 | 42 | #### Python 43 | 44 | ```python 45 | ``` 46 | 47 | ## License 48 | 49 | - MIT 50 | -------------------------------------------------------------------------------- /LeetCode/088-Merge-Sorted-Array/088-Merge-Sorted-Array.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution_1 { 4 | // 20 ms 5 | func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { 6 | guard nums1.count >= m + n else { fatalError("nums1 length is not enough.") } 7 | nums1 = (Array(nums1[0..= m + n else { fatalError("nums1 length is not enough.") } 15 | var p1 = 0 16 | var p2 = 0 17 | var all = [Int]() 18 | for _ in 0..= m { 20 | all.append(contentsOf: Array(nums2[p2...])) 21 | break 22 | } 23 | if p2 >= n { 24 | all.append(contentsOf: Array(nums1[p1...])) 25 | break 26 | } 27 | 28 | if nums1[p1] < nums2[p2] { 29 | all.append(nums1[p1]) 30 | p1 += 1 31 | } else { 32 | all.append(nums2[p2]) 33 | p2 += 1 34 | } 35 | } 36 | nums1 = Array(all[0.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/088-Merge-Sorted-Array/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 088 Merge Sorted Array 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution_1 { 13 | // 20 ms 14 | func merge(_ nums1: inout [Int], _ m: Int, _ nums2: [Int], _ n: Int) { 15 | guard nums1.count >= m + n else { fatalError("nums1 length is not enough.") } 16 | nums1 = (Array(nums1[0..= m + n else { fatalError("nums1 length is not enough.") } 24 | var p1 = 0 25 | var p2 = 0 26 | var all = [Int]() 27 | for _ in 0..= m { 29 | all.append(contentsOf: Array(nums2[p2...])) 30 | break 31 | } 32 | if p2 >= n { 33 | all.append(contentsOf: Array(nums1[p1...])) 34 | break 35 | } 36 | 37 | if nums1[p1] < nums2[p2] { 38 | all.append(nums1[p1]) 39 | p1 += 1 40 | } else { 41 | all.append(nums2[p2]) 42 | p2 += 1 43 | } 44 | } 45 | nums1 = Array(all[0.. Bool { 30 | if p == nil && q == nil { return true } 31 | if p == nil && q != nil { return false } 32 | if p != nil && q == nil { return false } 33 | if (p?.left == nil && q?.left != nil) || (q?.left == nil && p?.left != nil) { return false } 34 | if (p?.right == nil && q?.right != nil) || (q?.right == nil && p?.right != nil) { return false } 35 | 36 | if p?.left != nil { 37 | if p?.right != nil { 38 | return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right) && p!.val == q!.val 39 | } else { 40 | return isSameTree(p?.left, q?.left) && p!.val == q!.val 41 | } 42 | } else { 43 | if p?.right != nil { 44 | return isSameTree(p?.right, q?.right) && p!.val == q!.val 45 | } else { 46 | return p!.val == q!.val 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /LeetCode/100-Same-Tree/100-Same-Tree.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/100-Same-Tree/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 100 Same Tree 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 12 ms 14 | func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { 15 | if p == nil && q == nil { return true } 16 | if p == nil && q != nil { return false } 17 | if p != nil && q == nil { return false } 18 | if (p?.left == nil && q?.left != nil) || (q?.left == nil && p?.left != nil) { return false } 19 | if (p?.right == nil && q?.right != nil) || (q?.right == nil && p?.right != nil) { return false } 20 | 21 | if p?.left != nil { 22 | if p?.right != nil { 23 | return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right) && p!.val == q!.val 24 | } else { 25 | return isSameTree(p?.left, q?.left) && p!.val == q!.val 26 | } 27 | } else { 28 | if p?.right != nil { 29 | return isSameTree(p?.right, q?.right) && p!.val == q!.val 30 | } else { 31 | return p!.val == q!.val 32 | } 33 | } 34 | } 35 | } 36 | ``` 37 | 38 | #### Go 39 | 40 | ```go 41 | ``` 42 | 43 | #### Python 44 | 45 | ```python 46 | ``` 47 | 48 | ## License 49 | 50 | - MIT 51 | -------------------------------------------------------------------------------- /LeetCode/101-Symmetric-Tree/101-Symmetric-Tree.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * public var val: Int 7 | * public var left: TreeNode? 8 | * public var right: TreeNode? 9 | * public init(_ val: Int) { 10 | * self.val = val 11 | * self.left = nil 12 | * self.right = nil 13 | * } 14 | * } 15 | */ 16 | public class TreeNode { 17 | public var val: Int 18 | public var left: TreeNode? 19 | public var right: TreeNode? 20 | public init(_ val: Int) { 21 | self.val = val 22 | self.left = nil 23 | self.right = nil 24 | } 25 | } 26 | 27 | class Solution { 28 | // 20 ms 29 | func isSymmetric(_ root: TreeNode?) -> Bool { 30 | func isSymmetricNodes(_ a: TreeNode?, _ b: TreeNode?) -> Bool { 31 | if a == nil && b == nil { return true } 32 | if a == nil || b == nil { return false } 33 | 34 | return a?.val == b?.val && isSymmetricNodes(a?.left, b?.right) && isSymmetricNodes(a?.right, b?.left) 35 | } 36 | 37 | return isSymmetricNodes(root, root) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /LeetCode/101-Symmetric-Tree/101-Symmetric-Tree.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/101-Symmetric-Tree/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 101 Symmetric Tree 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 20 ms 14 | func isSymmetric(_ root: TreeNode?) -> Bool { 15 | func isSymmetricNodes(_ a: TreeNode?, _ b: TreeNode?) -> Bool { 16 | if a == nil && b == nil { return true } 17 | if a == nil || b == nil { return false } 18 | 19 | return a?.val == b?.val && isSymmetricNodes(a?.left, b?.right) && isSymmetricNodes(a?.right, b?.left) 20 | } 21 | 22 | return isSymmetricNodes(root, root) 23 | } 24 | } 25 | ``` 26 | 27 | #### Go 28 | 29 | ```go 30 | ``` 31 | 32 | #### Python 33 | 34 | ```python 35 | ``` 36 | 37 | ## License 38 | 39 | - MIT 40 | -------------------------------------------------------------------------------- /LeetCode/104-Maximum-Depth-of-Binary-Tree/104-Maximum-Depth-of-Binary-Tree.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * public var val: Int 7 | * public var left: TreeNode? 8 | * public var right: TreeNode? 9 | * public init(_ val: Int) { 10 | * self.val = val 11 | * self.left = nil 12 | * self.right = nil 13 | * } 14 | * } 15 | */ 16 | public class TreeNode { 17 | public var val: Int 18 | public var left: TreeNode? 19 | public var right: TreeNode? 20 | public init(_ val: Int) { 21 | self.val = val 22 | self.left = nil 23 | self.right = nil 24 | } 25 | } 26 | 27 | class Solution { 28 | // 36 ms 29 | func maxDepth(_ root: TreeNode?) -> Int { 30 | guard let node = root else { return 0 } 31 | var depth = 1 32 | 33 | if node.left != nil || node.right != nil { 34 | depth += max(maxDepth(node.left), maxDepth(node.right)) 35 | } 36 | 37 | return depth 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /LeetCode/104-Maximum-Depth-of-Binary-Tree/104-Maximum-Depth-of-Binary-Tree.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/104-Maximum-Depth-of-Binary-Tree/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 104 Maximum Depth of Binary Tree 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 36 ms 14 | func maxDepth(_ root: TreeNode?) -> Int { 15 | guard let node = root else { return 0 } 16 | var depth = 1 17 | 18 | if node.left != nil || node.right != nil { 19 | depth += max(maxDepth(node.left), maxDepth(node.right)) 20 | } 21 | 22 | return depth 23 | } 24 | } 25 | ``` 26 | 27 | #### Go 28 | 29 | ```go 30 | ``` 31 | 32 | #### Python 33 | 34 | ```python 35 | ``` 36 | 37 | ## License 38 | 39 | - MIT 40 | -------------------------------------------------------------------------------- /LeetCode/107-Binary-Tree-Level-Order-Traversal-II/107-Binary-Tree-Level-Order-Traversal-II.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * public var val: Int 7 | * public var left: TreeNode? 8 | * public var right: TreeNode? 9 | * public init(_ val: Int) { 10 | * self.val = val 11 | * self.left = nil 12 | * self.right = nil 13 | * } 14 | * } 15 | */ 16 | 17 | public class TreeNode { 18 | public var val: Int 19 | public var left: TreeNode? 20 | public var right: TreeNode? 21 | public init(_ val: Int) { 22 | self.val = val 23 | self.left = nil 24 | self.right = nil 25 | } 26 | } 27 | 28 | class Solution { 29 | // 16 ms 30 | func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { 31 | func nextLevelNodes(_ nodes: [TreeNode]) -> [TreeNode] { 32 | return nodes.reduce([TreeNode]()) { result, node in 33 | var result = result 34 | if let left = node.left { 35 | result.append(left) 36 | } 37 | 38 | if let right = node.right { 39 | result.append(right) 40 | } 41 | 42 | return result 43 | } 44 | } 45 | 46 | guard let root = root else { return [] } 47 | var result = [[Int]]() 48 | var nodes = [root] 49 | while nodes.count != 0 { 50 | result.append(nodes.reduce([Int]()) { $0 + [$1.val] }) 51 | nodes = nextLevelNodes(nodes) 52 | } 53 | return result.reversed() 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /LeetCode/107-Binary-Tree-Level-Order-Traversal-II/107-Binary-Tree-Level-Order-Traversal-II.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/107-Binary-Tree-Level-Order-Traversal-II/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 107 Binary Tree Level Order Traversal II 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 16 ms 14 | func levelOrderBottom(_ root: TreeNode?) -> [[Int]] { 15 | func nextLevelNodes(_ nodes: [TreeNode]) -> [TreeNode] { 16 | return nodes.reduce([TreeNode]()) { result, node in 17 | var result = result 18 | if let left = node.left { 19 | result.append(left) 20 | } 21 | 22 | if let right = node.right { 23 | result.append(right) 24 | } 25 | 26 | return result 27 | } 28 | } 29 | 30 | guard let root = root else { return [] } 31 | var result = [[Int]]() 32 | var nodes = [root] 33 | while nodes.count != 0 { 34 | result.append(nodes.reduce([Int]()) { $0 + [$1.val] }) 35 | nodes = nextLevelNodes(nodes) 36 | } 37 | return result.reversed() 38 | } 39 | } 40 | ``` 41 | 42 | #### Go 43 | 44 | ```go 45 | ``` 46 | 47 | #### Python 48 | 49 | ```python 50 | ``` 51 | 52 | ## License 53 | 54 | - MIT 55 | -------------------------------------------------------------------------------- /LeetCode/108-Convert-Sorted-Array-to-Binary-Search-Tree/108-Convert-Sorted-Array-to-Binary-Search-Tree.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * public class TreeNode { 6 | * public var val: Int 7 | * public var left: TreeNode? 8 | * public var right: TreeNode? 9 | * public init(_ val: Int) { 10 | * self.val = val 11 | * self.left = nil 12 | * self.right = nil 13 | * } 14 | * } 15 | */ 16 | 17 | public class TreeNode { 18 | public var val: Int 19 | public var left: TreeNode? 20 | public var right: TreeNode? 21 | public init(_ val: Int) { 22 | self.val = val 23 | self.left = nil 24 | self.right = nil 25 | } 26 | } 27 | 28 | class Solution { 29 | // 44 ms 30 | func sortedArrayToBST(_ nums: [Int]) -> TreeNode? { 31 | guard !nums.isEmpty else { return nil } 32 | var nums = nums 33 | 34 | let root = TreeNode(nums[(nums.count - 1) / 2]) 35 | let left = [Int](nums[0..<(nums.count - 1) / 2]) 36 | let right = [Int](nums[(nums.count - 1) / 2 + 1.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/108-Convert-Sorted-Array-to-Binary-Search-Tree/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 108 Convert Sorted Array to Binary Search Tree 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 44 ms 14 | func sortedArrayToBST(_ nums: [Int]) -> TreeNode? { 15 | guard !nums.isEmpty else { return nil } 16 | var nums = nums 17 | 18 | let root = TreeNode(nums[(nums.count - 1) / 2]) 19 | let left = [Int](nums[0..<(nums.count - 1) / 2]) 20 | let right = [Int](nums[(nums.count - 1) / 2 + 1.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/110-Balanced-Binary-Tree/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 110 Balanced Binary Tree 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | ``` 13 | 14 | #### Go 15 | 16 | ```go 17 | ``` 18 | 19 | #### Python 20 | 21 | ```python 22 | ``` 23 | 24 | ## License 25 | 26 | - MIT 27 | -------------------------------------------------------------------------------- /LeetCode/118-Pascal's-Triangle/118-Pascal's-Triangle.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 4 ms 5 | func generate(_ numRows: Int) -> [[Int]] { 6 | if numRows <= 0 { return [] } 7 | if numRows == 1 { return [[1]] } 8 | if numRows == 2 { return [[1], [1, 1]] } 9 | 10 | var last = generate(numRows - 1) 11 | var new = (1.. Int in 12 | return last.last![v] + last.last![v-1] 13 | } 14 | 15 | new.insert(1, at: 0) 16 | new.append(1) 17 | 18 | last.append(new) 19 | return last 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /LeetCode/118-Pascal's-Triangle/118-Pascal's-Triangle.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/118-Pascal's-Triangle/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 118 Pascal's Triangle 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```swift 12 | class Solution { 13 | // 4 ms 14 | func generate(_ numRows: Int) -> [[Int]] { 15 | if numRows <= 0 { return [] } 16 | if numRows == 1 { return [[1]] } 17 | if numRows == 2 { return [[1], [1, 1]] } 18 | 19 | var last = generate(numRows - 1) 20 | var new = (1.. Int in 21 | return last.last![v] + last.last![v-1] 22 | } 23 | 24 | new.insert(1, at: 0) 25 | new.append(1) 26 | 27 | last.append(new) 28 | return last 29 | } 30 | } 31 | ``` 32 | 33 | #### Go 34 | 35 | ```go 36 | ``` 37 | 38 | #### Python 39 | 40 | ```python 41 | ``` 42 | 43 | ## License 44 | 45 | - MIT 46 | -------------------------------------------------------------------------------- /LeetCode/498-Diagonal-Traverse/498-Diagonal-Traverse.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 1376 ms 5 | func findDiagonalOrder(_ matrix: [[Int]]) -> [Int] { 6 | guard !matrix.isEmpty, !matrix[0].isEmpty else { return [] } 7 | let m = matrix.count 8 | let n = matrix[0].count 9 | 10 | var result = [Int]() 11 | for i in 0..= m || j >= n { continue } 15 | result.append(matrix[i-j][j]) 16 | } 17 | } else { 18 | for j in 0..= m || i-j >= n { continue } 20 | result.append(matrix[j][i-j]) 21 | } 22 | } 23 | } 24 | 25 | return result 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /LeetCode/498-Diagonal-Traverse/498-Diagonal-Traverse.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/498-Diagonal-Traverse/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 498 Diagonal Traverse 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```swift 12 | class Solution { 13 | // 1376 ms 14 | func findDiagonalOrder(_ matrix: [[Int]]) -> [Int] { 15 | guard !matrix.isEmpty, !matrix[0].isEmpty else { return [] } 16 | let m = matrix.count 17 | let n = matrix[0].count 18 | 19 | var result = [Int]() 20 | for i in 0..= m || j >= n { continue } 24 | result.append(matrix[i-j][j]) 25 | } 26 | } else { 27 | for j in 0..= m || i-j >= n { continue } 29 | result.append(matrix[j][i-j]) 30 | } 31 | } 32 | } 33 | 34 | return result 35 | } 36 | } 37 | ``` 38 | 39 | #### Go 40 | 41 | ```go 42 | ``` 43 | 44 | #### Python 45 | 46 | ```python 47 | ``` 48 | 49 | ## License 50 | 51 | - MIT 52 | -------------------------------------------------------------------------------- /LeetCode/509-Fibonacci-Number/509-Fibonacci-Number.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 4 ms 5 | func fib(_ N: Int) -> Int { 6 | guard N > 1 else { 7 | return N 8 | } 9 | 10 | var first = 0 11 | var second = 1 12 | 13 | for _ in 0.. 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/509-Fibonacci-Number/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 509 Fibonacci Number 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```swift 12 | ``` 13 | 14 | #### Go 15 | 16 | ```go 17 | ``` 18 | 19 | #### Python 20 | 21 | ```python 22 | ``` 23 | 24 | ## License 25 | 26 | - MIT 27 | -------------------------------------------------------------------------------- /LeetCode/724-Find-Pivot-Index/724-Find-Pivot-Index.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 156 ms 5 | func pivotIndex(_ nums: [Int]) -> Int { 6 | guard nums.count > 2 else { return -1 } 7 | 8 | let sum = nums.reduce(0, +) 9 | var leftSum = 0 10 | for t in nums.enumerated() { 11 | if leftSum * 2 == sum - t.element { 12 | return t.offset 13 | } 14 | leftSum += t.element 15 | } 16 | 17 | return -1 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /LeetCode/724-Find-Pivot-Index/724-Find-Pivot-Index.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/724-Find-Pivot-Index/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 724 Find Pivot Index 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```swift 12 | class Solution { 13 | // 164 ms 14 | func pivotIndex(_ nums: [Int]) -> Int { 15 | let sum = nums.reduce(0, +) 16 | var leftSum = 0.0 17 | for t in nums.enumerated() { 18 | if leftSum == Double(sum - t.element) / 2.0 { 19 | return t.offset 20 | } 21 | leftSum += Double(t.element) 22 | } 23 | 24 | return -1 25 | } 26 | } 27 | ``` 28 | 29 | #### Go 30 | 31 | ```go 32 | ``` 33 | 34 | #### Python 35 | 36 | ```python 37 | ``` 38 | 39 | ## License 40 | 41 | - MIT 42 | -------------------------------------------------------------------------------- /LeetCode/747-Largest-Number-At-Least-Twice-of-Others/747-Largest-Number-At-Least-Twice-of-Others.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | class Solution { 4 | // 16 ms 5 | func dominantIndex(_ nums: [Int]) -> Int { 6 | guard !nums.isEmpty else { return -1 } 7 | 8 | var maxIndex = 0 9 | 10 | for t in nums.enumerated() { 11 | maxIndex = t.element >= nums[maxIndex] ? t.offset : maxIndex 12 | } 13 | 14 | for t in nums.enumerated() { 15 | guard t.offset != maxIndex else { continue } 16 | 17 | if t.element * 2 > nums[maxIndex] { 18 | return -1 19 | } 20 | } 21 | 22 | return maxIndex 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /LeetCode/747-Largest-Number-At-Least-Twice-of-Others/747-Largest-Number-At-Least-Twice-of-Others.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/747-Largest-Number-At-Least-Twice-of-Others/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## 747 Largest Number At Least Twice of Others 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```Swift 12 | class Solution { 13 | // 16 ms 14 | func dominantIndex(_ nums: [Int]) -> Int { 15 | guard !nums.isEmpty else { return -1 } 16 | 17 | var maxIndex = 0 18 | 19 | for t in nums.enumerated() { 20 | maxIndex = t.element >= nums[maxIndex] ? t.offset : maxIndex 21 | } 22 | 23 | for t in nums.enumerated() { 24 | guard t.offset != maxIndex else { continue } 25 | 26 | if t.element * 2 > nums[maxIndex] { 27 | return -1 28 | } 29 | } 30 | 31 | return maxIndex 32 | } 33 | } 34 | ``` 35 | 36 | #### Go 37 | 38 | ```go 39 | ``` 40 | 41 | #### Python 42 | 43 | ```python 44 | ``` 45 | 46 | ## License 47 | 48 | - MIT 49 | -------------------------------------------------------------------------------- /LeetCode/PLACE_HOLDER/NO.-PROBLEM_NAME.playground/Contents.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | 3 | -------------------------------------------------------------------------------- /LeetCode/PLACE_HOLDER/NO.-PROBLEM_NAME.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /LeetCode/PLACE_HOLDER/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | > Algorithms implemented in Swift/Go/Python. 4 | 5 | ## NO. PROBLEM_NAME 6 | 7 | ### Solutions 8 | 9 | #### Swift 10 | 11 | ```swift 12 | ``` 13 | 14 | #### Go 15 | 16 | ```go 17 | ``` 18 | 19 | #### Python 20 | 21 | ```python 22 | ``` 23 | 24 | ## License 25 | 26 | - MIT 27 | -------------------------------------------------------------------------------- /LeetCode/PLACE_HOLDER/new-lc.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | max_num_digits=3 4 | main_path=$(cd `dirname $0`; pwd)/.. 5 | # echo $main_path 6 | 7 | xx=* 8 | 9 | if [ -n "$*" ] && [ -n "$2" ]; then 10 | standard_name=$* 11 | 12 | # 0. Generate new name with format 13 | # eg. 1. Two Sum -> 001-Two-Sum & 001 Two Sum 14 | num=`echo $standard_name | cut -d \. -f 1` 15 | loop_count=`expr $max_num_digits - ${#num}` 16 | 17 | while [ $loop_count -gt 0 ] 18 | do 19 | num="0$num" 20 | loop_count=`expr $loop_count - 1` 21 | done 22 | 23 | name=`echo $standard_name | cut -d \. -f 2` 24 | 25 | display_name="$num$name" 26 | folder_name=$num`echo ${name// /-}` 27 | 28 | new_path="$main_path/$folder_name" 29 | 30 | playground_original_path=$main_path/PLACE_HOLDER/NO.-PROBLEM_NAME.playground 31 | playground_new_path=$new_path/$folder_name.playground 32 | readme_original_path=$main_path/PLACE_HOLDER/README.md 33 | readme_new_path=$new_path/README.md 34 | 35 | # echo $playground_original_path 36 | # echo $playground_new_path 37 | # echo $readme_original_path 38 | # echo $readme_new_path 39 | 40 | if [ ! -x "$new_path" ] && [ ! -x "$playground_new_path" ] && [ ! -x "$readme_new_path" ]; then 41 | # 1. Create new folder 42 | mkdir "$new_path" 43 | 44 | # 2. Copy files 45 | cp -r $playground_original_path $playground_new_path 46 | cp -r $readme_original_path $readme_new_path 47 | 48 | # 3. Update problem's info in README.md 49 | if [ `uname` = "Linux" ]; then 50 | sed -i "s/NO. PROBLEM_NAME/$display_name/" "$readme_new_path" 51 | elif [ `uname` = "Darwin" ]; then 52 | sed -i "" "s/NO. PROBLEM_NAME/$display_name/" "$readme_new_path" 53 | else 54 | echo "⚠️ ERROR: Your system is not supported." 55 | fi 56 | 57 | echo "🎉 DONE!" 58 | else 59 | echo "⚠️ ERROR: The folder or files is already exist. ⚠️" 60 | fi 61 | # 4. Print new folder path for repo's README 62 | echo "" 63 | echo "💻 Display name: $display_name" 64 | echo "📁 Folder name: $folder_name" 65 | echo "- [$display_name](/LeetCode/$folder_name)" 66 | else 67 | echo "⚠️ ERROR: Please input problem's standard name from LeetCode website (eg. 1. Two Sum). ⚠️" 68 | fi 69 | -------------------------------------------------------------------------------- /LeetCode/delete-middle-node-lcci: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingcos/Swift-X-Algorithms/c9eeb03e44455a032ffb59350d020922e0caa512/LeetCode/delete-middle-node-lcci -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms & Data Structures implemented in Swift X (X = 4.2). 4 | 5 | [中文版 README](README_CN.md) 6 | 7 | ## Preface 8 | 9 | Hello! 10 | 11 | Algorithms is the soul of programs. But I am a green hand in this field. Now I am trying to learn them well, to open my mind in thinking how to write elegant code. 12 | 13 | If my code did help you, would you please give me a Star 🌟? It will courage me to move on! Thank you! 14 | 15 | **No doubt that I would made some mistakes in it, if you find some bugs, please issue me. I am looking forward to discuss with you about the magic of Swift! Thank you!** 16 | 17 | - [Twitter](https://twitter.com/mmdadao) 18 | - [WeiBo (zh-CN)](http://weibo.com/375975847) 19 | - [Perspective (Blog)](https://github.com/kingcos/Perspective) 20 | 21 | ## Contents 22 | 23 | - **Sort** 24 | - [Selection Sort](/Sort/01-SelectionSort) 25 | - [Insertion Sort](/Sort/02-InsertionSort) 26 | - [Insertion Sort Advanced](/Sort/03-InsertionSort-Advanced) 27 | - [Bubble Sort](/Sort/04-BubbleSort) 28 | - [Shell Sort](/Sort/05-ShellSort) 29 | - [Merge Sort](/Sort/06-MergeSort) 30 | - [Merge Sort Advanced](/Sort/07-MergeSort-Advanced) 31 | - [Merge Sort Bottom Up](/Sort/08-MergeSort-BottomUp) 32 | - [Quick Sort](/Sort/09-QuickSort) 33 | - [Quick Sort Randomized](/Sort/10-QuickSort-Randomized) 34 | - [Quick Sort 2 Way](/Sort/11-QuickSort-2-Way) 35 | - [Quick Sort 3 Way](/Sort/12-QuickSort-3-Way) 36 | - [Heap Sort](/Sort/13-HeapSort) 37 | - [Heap Sort Heapify](/Sort/14-HeapSort-Heapify) 38 | 39 | - **Search** 40 | - [Binary Search Iteratively](/Search/01-BinarySearch-Iteratively) 41 | - [Binary Search Recursively](/Search/02-BinarySearch-Recursively) 42 | 43 | - **Data Structure** 44 | - [Heap](/DataStructure/01-Heap) 45 | 46 | - **LeetCode** 47 | - [001 Two Sum](/LeetCode/001-Two-Sum) 48 | - [007 Reverse Integer](/LeetCode/007-Reverse-Integer) 49 | - [009 Palindrome Number](/LeetCode/009-Palindrome-Number) 50 | - [014 Longest Common Prefix](/LeetCode/014-Longest-Common-Prefix) 51 | - [020 Valid Parentheses](/LeetCode/020-Valid-Parentheses) 52 | - [021 Merge Two Sorted Lists](/LeetCode/021-Merge-Two-Sorted-Lists) 53 | - [026 Remove Duplicates from Sorted Array](/LeetCode/026-Remove-Duplicates-from-Sorted-Array) 54 | - [027 Remove Element](/LeetCode/027-Remove-Element) 55 | - [028 Implement strStr()](/LeetCode/028-Implement-strStr()) 56 | - [035 Search Insert Position](/LeetCode/035-Search-Insert-Position) 57 | - [038 Count and Say](/LeetCode/038-Count-and-Say) 58 | - [053 Maximum Subarray](/LeetCode/053-Maximum-Subarray) 59 | - [058 Length of Last Word](/LeetCode/058-Length-of-Last-Word) 60 | - [066 Plus One](/LeetCode/066-Plus-One) 61 | - [067 Add Binary](/LeetCode/067-Add-Binary) 62 | - [069 Sqrt(x)](/LeetCode/069-Sqrt(x)) 63 | - [070 Climbing Stairs](/LeetCode/070-Climbing-Stairs) 64 | - [083 Remove Duplicates from Sorted List](/LeetCode/083-Remove-Duplicates-from-Sorted-List) 65 | - [088 Merge Sorted Array](/LeetCode/088-Merge-Sorted-Array) 66 | - [100 Same Tree](/LeetCode/100-Same-Tree) 67 | - [101 Symmetric Tree](/LeetCode/101-Symmetric-Tree) 68 | - [104 Maximum Depth of Binary Tree](/LeetCode/104-Maximum-Depth-of-Binary-Tree) 69 | - [107 Binary Tree Level Order Traversal II](/LeetCode/107-Binary-Tree-Level-Order-Traversal-II) 70 | - [108 Convert Sorted Array to Binary Search Tree](/LeetCode/108-Convert-Sorted-Array-to-Binary-Search-Tree) 71 | 72 | ## Why Swift X? 73 | 74 | Swift is a new-born programming language which update continuously. It has a lot of new features and grammar changes between different versions before its ABI is stable. 75 | 76 | Currently, the newest version of Swift is 4.2 (with Xcode 10). 77 | 78 | So I try to use X to represent the newest version of Swift and adapt to the newest Xcode. 79 | 80 | ## Reference 81 | 82 | - [Algorithms & Data Structures in C++ (zh-CN)](http://coding.imooc.com/class/71.html) 83 | - [Algorithms, Part I](https://www.coursera.org/learn/introduction-to-algorithms) 84 | - [Algorithms (4th Edition)](https://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X/ref=sr_1_2?ie=UTF8&qid=1481002530&sr=8-2&keywords=algorithms) 85 | - [raywenderlich/swift-algorithm-club](https://github.com/raywenderlich/swift-algorithm-club) 86 | 87 | ## Revision History 88 | 89 | - [Swift 3.x](https://github.com/kingcos/Swift-X-Algorithms/tree/swift_3.x) 90 | - [Swift 4.x](https://github.com/kingcos/Swift-X-Algorithms/tree/swift_4.x) 91 | 92 | ## LICENSE 93 | 94 | - MIT 95 | -------------------------------------------------------------------------------- /README_CN.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | 使用 Swift X (X = 4.2) 实现的算法和数据结构。 4 | 5 | [English Version README](README.md) 6 | 7 | ## 前言 8 | 9 | 算法在程序设计中的重要性众所周知,而算法着重在思想方面,而非拘泥于具体的程序设计语言,本人目前在努力学习算法,目的是开阔思想,锻炼思维。所以本仓库将个人刷题,学习算法过程中的心得分享,并使用 Swift 4.2 实现。 10 | 11 | 本仓库的更新将跟随个人学习进度同步发布,如果确有帮助到您,您可以根据需要点个喜欢 ❤️,加个 Star 🌟,那就再好不过啦。 12 | 13 | **由于能力有限,虽在不断学习,但不免有错误,希望您能在 GitHub 中提出 Issue 或者评论告诉我,我都会细心研究,改正错误。谢谢!** 14 | 15 | - [微博](http://weibo.com/375975847) 16 | - [Perspective(博客)](https://github.com/kingcos/Perspective) 17 | - [Twitter](https://twitter.com/mmdadao) 18 | 19 | ## 目录 20 | 21 | - **排序** 22 | - [选择排序](/Sort/01-SelectionSort) 23 | - [插入排序](/Sort/02-InsertionSort) 24 | - [插入排序-优化](/Sort/03-InsertionSort-Advanced) 25 | - [冒泡排序](/Sort/04-BubbleSort) 26 | - [希尔排序](/Sort/05-ShellSort) 27 | - [归并排序](/Sort/06-MergeSort) 28 | - [归并排序-优化](/Sort/07-MergeSort-Advanced) 29 | - [归并排序-自底向上](/Sort/08-MergeSort-BottomUp) 30 | - [快速排序](/Sort/09-QuickSort) 31 | - [快速排序-随机化](/Sort/10-QuickSort-Randomized) 32 | - [快速排序-两路](/Sort/11-QuickSort-2-Way) 33 | - [快速排序-三路](/Sort/12-QuickSort-3-Way) 34 | - [堆排序](/Sort/13-HeapSort) 35 | - [堆排序-优化](/Sort/14-HeapSort-Advanced) 36 | 37 | - **查找** 38 | - [二分查找-迭代](/Search/01-BinarySearch-Iteratively) 39 | - [二分查找-递归](/Search/02-BinarySearch-Recursively) 40 | 41 | - **数据结构** 42 | - [堆](/DataStructure/01-Heap) 43 | 44 | - **LeetCode** 45 | - [001 Two Sum](/LeetCode/001-Two-Sum) 46 | - [007 Reverse Integer](/LeetCode/007-Reverse-Integer) 47 | - [009 Palindrome Number](/LeetCode/009-Palindrome-Number) 48 | - [014 Longest Common Prefix](/LeetCode/014-Longest-Common-Prefix) 49 | - [020 Valid Parentheses](/LeetCode/020-Valid-Parentheses) 50 | - [021 Merge Two Sorted Lists](/LeetCode/021-Merge-Two-Sorted-Lists) 51 | - [026 Remove Duplicates from Sorted Array](/LeetCode/026-Remove-Duplicates-from-Sorted-Array) 52 | - [027 Remove Element](/LeetCode/027-Remove-Element) 53 | - [028 Implement strStr()](/LeetCode/028-Implement-strStr()) 54 | - [035 Search Insert Position](/LeetCode/035-Search-Insert-Position) 55 | - [038 Count and Say](/LeetCode/038-Count-and-Say) 56 | - [053 Maximum Subarray](/LeetCode/053-Maximum-Subarray) 57 | - [058 Length of Last Word](/LeetCode/058-Length-of-Last-Word) 58 | - [066 Plus One](/LeetCode/066-Plus-One) 59 | - [067 Add Binary](/LeetCode/067-Add-Binary) 60 | - [069 Sqrt(x)](/LeetCode/069-Sqrt(x)) 61 | - [070 Climbing Stairs](/LeetCode/070-Climbing-Stairs) 62 | - [083 Remove Duplicates from Sorted List](/LeetCode/083-Remove-Duplicates-from-Sorted-List) 63 | - [088 Merge Sorted Array](/LeetCode/088-Merge-Sorted-Array) 64 | - [100 Same Tree](/LeetCode/100-Same-Tree) 65 | - [101 Symmetric Tree](/LeetCode/101-Symmetric-Tree) 66 | - [104 Maximum Depth of Binary Tree](/LeetCode/104-Maximum-Depth-of-Binary-Tree) 67 | - [107 Binary Tree Level Order Traversal II](/LeetCode/107-Binary-Tree-Level-Order-Traversal-II) 68 | - [108 Convert Sorted Array to Binary Search Tree](/LeetCode/108-Convert-Sorted-Array-to-Binary-Search-Tree) 69 | 70 | ## 何为 Swift X? 71 | 72 | Swift 是一门与时俱进的语言,在 ABI 稳定前,每次更新都会加入很多新的改进,以及语法层面的改动。 73 | 74 | 现在,Swift 的最新版本为 4.2(Xcode 10)。 75 | 76 | 所以我尝试使用 X 来概括 Swift 的版本,并将更新代码以适配当前最新的 Xcode。 77 | 78 | ## 参考 79 | 80 | - [算法与数据结构 C++ 精解](http://coding.imooc.com/class/71.html) 81 | - [Algorithms, Part I](https://www.coursera.org/learn/introduction-to-algorithms) 82 | - [Algorithms (4th Edition)](https://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X/ref=sr_1_2?ie=UTF8&qid=1481002530&sr=8-2&keywords=algorithms) 83 | - [raywenderlich/swift-algorithm-club](https://github.com/raywenderlich/swift-algorithm-club) 84 | 85 | ## 修订历史 86 | 87 | - [Swift 3.x](https://github.com/kingcos/Swift-X-Algorithms/tree/swift_3.x) 88 | - [Swift 4.2](https://github.com/kingcos/Swift-X-Algorithms/tree/master) 89 | 90 | ## 许可 91 | 92 | - MIT 93 | -------------------------------------------------------------------------------- /Search/01-BinarySearch-Iteratively/01-BinarySearch-Iteratively.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Search/01-BinarySearch-Iteratively/01-BinarySearch-Iteratively.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Search/01-BinarySearch-Iteratively/01-BinarySearch-Iteratively.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingcos/Swift-X-Algorithms/c9eeb03e44455a032ffb59350d020922e0caa512/Search/01-BinarySearch-Iteratively/01-BinarySearch-Iteratively.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Search/01-BinarySearch-Iteratively/01-BinarySearch-Iteratively.xcodeproj/xcuserdata/kingcos.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 01-BinarySearch-Iteratively.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Search/01-BinarySearch-Iteratively/01-BinarySearch-Iteratively/main.swift: -------------------------------------------------------------------------------- 1 | // 2 | // main.swift 3 | // 01-BinarySearch-Iteratively 4 | // 5 | // Created by kingcos on 05/09/2017. 6 | // Copyright © 2017 kingcos. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | func binarySearchIteratively(_ target: T, 12 | in arr: [T]) -> Int? { 13 | // 下标下限 14 | var lowerBound = 0 15 | // 下标上限 16 | var upperBound = arr.count - 1 17 | 18 | while lowerBound <= upperBound { 19 | let middle = lowerBound + (upperBound - lowerBound) / 2 20 | 21 | if arr[middle] == target { 22 | return middle 23 | } 24 | 25 | if target < arr[middle] { 26 | upperBound = middle - 1 27 | } else { 28 | lowerBound = middle + 1 29 | } 30 | } 31 | 32 | return nil 33 | } 34 | 35 | let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] 36 | print(binarySearchIteratively(67, in: numbers) ?? -1) 37 | print(binarySearchIteratively(24, in: numbers) ?? -1) 38 | -------------------------------------------------------------------------------- /Search/01-BinarySearch-Iteratively/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func binarySearchIteratively(_ target: T, 9 | in arr: [T]) -> Int? { 10 | // 下标下限 11 | var lowerBound = 0 12 | // 下标上限 13 | var upperBound = arr.count - 1 14 | 15 | while lowerBound <= upperBound { 16 | let middle = lowerBound + (upperBound - lowerBound) / 2 17 | 18 | if arr[middle] == target { 19 | return middle 20 | } 21 | 22 | if target < arr[middle] { 23 | upperBound = middle - 1 24 | } else { 25 | lowerBound = middle + 1 26 | } 27 | } 28 | 29 | return nil 30 | } 31 | ``` 32 | 33 | ## License 34 | 35 | MIT 36 | -------------------------------------------------------------------------------- /Search/02-BinarySearch-Recursively/02-BinarySearch-Recursively.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Search/02-BinarySearch-Recursively/02-BinarySearch-Recursively.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Search/02-BinarySearch-Recursively/02-BinarySearch-Recursively.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingcos/Swift-X-Algorithms/c9eeb03e44455a032ffb59350d020922e0caa512/Search/02-BinarySearch-Recursively/02-BinarySearch-Recursively.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Search/02-BinarySearch-Recursively/02-BinarySearch-Recursively.xcodeproj/xcuserdata/kingcos.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 02-BinarySearch-Recursively.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Search/02-BinarySearch-Recursively/02-BinarySearch-Recursively/main.swift: -------------------------------------------------------------------------------- 1 | // 2 | // main.swift 3 | // 02-BinarySearch-Recursively 4 | // 5 | // Created by kingcos on 05/09/2017. 6 | // Copyright © 2017 kingcos. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | 11 | func binarySearchRecursively(_ target: T, 12 | in arr: [T]) -> Int? { 13 | func _binarySearchRecursively(_ target: T, 14 | in arr: [T], 15 | of range: Range) -> Int? { 16 | guard range.lowerBound < range.upperBound else { return nil } 17 | 18 | let middle = range.lowerBound + (range.upperBound - range.lowerBound) / 2 19 | 20 | if target == arr[middle] { 21 | return middle 22 | } 23 | 24 | if target < arr[middle] { 25 | return _binarySearchRecursively(target, in: arr, of: range.lowerBound ..< middle) 26 | } else { 27 | return _binarySearchRecursively(target, in: arr, of: middle + 1 ..< range.upperBound) 28 | } 29 | } 30 | 31 | return _binarySearchRecursively(target, in: arr, of: 0 ..< arr.count) 32 | } 33 | 34 | let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] 35 | print(binarySearchRecursively(67, in: numbers) ?? -1) 36 | print(binarySearchRecursively(24, in: numbers) ?? -1) 37 | -------------------------------------------------------------------------------- /Search/02-BinarySearch-Recursively/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func binarySearchRecursively(_ target: T, 9 | in arr: [T]) -> Int? { 10 | func _binarySearchRecursively(_ target: T, 11 | in arr: [T], 12 | of range: Range) -> Int? { 13 | guard range.lowerBound < range.upperBound else { return nil } 14 | 15 | let middle = range.lowerBound + (range.upperBound - range.lowerBound) / 2 16 | 17 | if target == arr[middle] { 18 | return middle 19 | } 20 | 21 | if target < arr[middle] { 22 | return _binarySearchRecursively(target, in: arr, of: range.lowerBound ..< middle) 23 | } else { 24 | return _binarySearchRecursively(target, in: arr, of: middle + 1 ..< range.upperBound) 25 | } 26 | } 27 | 28 | return _binarySearchRecursively(target, in: arr, of: 0 ..< arr.count) 29 | } 30 | ``` 31 | 32 | ## License 33 | 34 | MIT 35 | -------------------------------------------------------------------------------- /Sort/01-SelectionSort/01-SelectionSort.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/01-SelectionSort/01-SelectionSort.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Sort/01-SelectionSort/01-SelectionSort.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingcos/Swift-X-Algorithms/c9eeb03e44455a032ffb59350d020922e0caa512/Sort/01-SelectionSort/01-SelectionSort.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Sort/01-SelectionSort/01-SelectionSort.xcodeproj/xcuserdata/kingcos.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 01-SelectionSort.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Sort/01-SelectionSort/01-SelectionSort/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: inout Array, 12 | _ isNotOrdered: (T, T) -> Bool) { 13 | // 依次查找极值 14 | for i in 0..(_ arr: inout Array, 9 | _ isNotOrdered: (T, T) -> Bool) { 10 | // 依次查找极值 11 | for i in 0.. 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/02-InsertionSort/02-InsertionSort.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Sort/02-InsertionSort/02-InsertionSort.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingcos/Swift-X-Algorithms/c9eeb03e44455a032ffb59350d020922e0caa512/Sort/02-InsertionSort/02-InsertionSort.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Sort/02-InsertionSort/02-InsertionSort.xcodeproj/xcuserdata/kingcos.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 02-InsertionSort.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Sort/02-InsertionSort/02-InsertionSort/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool) { 12 | for i in 0..(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool) { 9 | for i in 0.. 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/03-InsertionSort-Advanced/03-InsertionSort-Advanced.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Sort/03-InsertionSort-Advanced/03-InsertionSort-Advanced.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingcos/Swift-X-Algorithms/c9eeb03e44455a032ffb59350d020922e0caa512/Sort/03-InsertionSort-Advanced/03-InsertionSort-Advanced.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Sort/03-InsertionSort-Advanced/03-InsertionSort-Advanced.xcodeproj/xcuserdata/kingcos.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 03-InsertionSort-Advanced.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Sort/03-InsertionSort-Advanced/03-InsertionSort-Advanced/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool) { 12 | for i in 0.. 0 && isNotOrdered(e, arr[j - 1]) { 18 | arr[j] = arr[j - 1] 19 | j -= 1 20 | } 21 | arr[j] = e 22 | } 23 | } 24 | 25 | TestHelper.checkSortAlgorithm(insertionSortAdvanced) 26 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(insertionSortAdvanced) 27 | -------------------------------------------------------------------------------- /Sort/03-InsertionSort-Advanced/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func insertionSortAdvanced(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool) { 9 | for i in 0.. 0 && isNotOrdered(e, arr[j - 1]) { 15 | arr[j] = arr[j - 1] 16 | j -= 1 17 | } 18 | arr[j] = e 19 | } 20 | } 21 | ``` 22 | 23 | ## License 24 | 25 | MIT 26 | -------------------------------------------------------------------------------- /Sort/04-BubbleSort/04-BubbleSort.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/04-BubbleSort/04-BubbleSort.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Sort/04-BubbleSort/04-BubbleSort.xcodeproj/xcuserdata/kingcos.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 04-BubbleSort.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Sort/04-BubbleSort/04-BubbleSort/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool) { 12 | for i in 0..(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool) { 9 | for i in 0.. 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/05-ShellSort/05-ShellSort.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Sort/05-ShellSort/05-ShellSort.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingcos/Swift-X-Algorithms/c9eeb03e44455a032ffb59350d020922e0caa512/Sort/05-ShellSort/05-ShellSort.xcodeproj/project.xcworkspace/xcuserdata/kingcos.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Sort/05-ShellSort/05-ShellSort.xcodeproj/xcuserdata/kingcos.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 05-ShellSort.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Sort/05-ShellSort/05-ShellSort/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool) { 12 | var h = 1 13 | while h < arr.count / 3 { 14 | h = 3 * h + 1 15 | } 16 | 17 | while h >= 1 { 18 | // Insertion Sort Advanced 19 | for i in h..= h && isNotOrdered(e, arr[j - 1]) { 25 | arr[j] = arr[j - h] 26 | j -= 1 27 | } 28 | arr[j] = e 29 | } 30 | h /= 3 31 | } 32 | } 33 | 34 | TestHelper.checkSortAlgorithm(shellSort) 35 | TestHelper.checkSortAlgorithm(shellSort, 10000) 36 | -------------------------------------------------------------------------------- /Sort/05-ShellSort/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func shellSort(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool) { 9 | var h = 1 10 | while h < arr.count / 3 { 11 | h = 3 * h + 1 12 | } 13 | 14 | while h >= 1 { 15 | // Insertion Sort Advanced 16 | for i in h..= h && isNotOrdered(e, arr[j - 1]) { 22 | arr[j] = arr[j - h] 23 | j -= 1 24 | } 25 | arr[j] = e 26 | } 27 | h /= 3 28 | } 29 | } 30 | ``` 31 | 32 | ## License 33 | 34 | MIT 35 | -------------------------------------------------------------------------------- /Sort/06-MergeSort/06-MergeSort.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/06-MergeSort/06-MergeSort.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Sort/06-MergeSort/06-MergeSort.xcodeproj/xcuserdata/kingcos.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | 06-MergeSort.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Sort/06-MergeSort/06-MergeSort/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 12 | // [0, mid) & [mid, arr.count) 13 | func merge(_ lArr: Array, _ rArr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 14 | var arr = lArr + rArr 15 | var l = 0, r = 0 16 | 17 | for i in 0..= lArr.count { 19 | arr[i] = rArr[r] 20 | r += 1 21 | } else if r >= rArr.count { 22 | arr[i] = lArr[l] 23 | l += 1 24 | } else if isNotOrdered(lArr[l], rArr[r]) { 25 | arr[i] = lArr[l] 26 | l += 1 27 | } else { 28 | arr[i] = rArr[r] 29 | r += 1 30 | } 31 | } 32 | 33 | return arr 34 | } 35 | 36 | guard arr.count > 1 else { return arr } 37 | 38 | let mid = arr.count / 2 39 | 40 | let lArr = mergeSort(Array(arr[0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 9 | // [0, mid) & [mid, arr.count) 10 | func merge(_ lArr: Array, _ rArr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 11 | var arr = lArr + rArr 12 | var l = 0, r = 0 13 | 14 | for i in 0..= lArr.count { 16 | arr[i] = rArr[r] 17 | r += 1 18 | } else if r >= rArr.count { 19 | arr[i] = lArr[l] 20 | l += 1 21 | } else if isNotOrdered(lArr[l], rArr[r]) { 22 | arr[i] = lArr[l] 23 | l += 1 24 | } else { 25 | arr[i] = rArr[r] 26 | r += 1 27 | } 28 | } 29 | 30 | return arr 31 | } 32 | 33 | guard arr.count > 1 else { return arr } 34 | 35 | let mid = arr.count / 2 36 | 37 | let lArr = mergeSort(Array(arr[0.. 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/07-MergeSort-Advanced/07-MergeSort-Advanced/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 12 | // [0, mid) & [mid, arr.count) 13 | func merge(_ lArr: Array, _ rArr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 14 | var arr = lArr + rArr 15 | var l = 0, r = 0 16 | 17 | for i in 0..= lArr.count { 19 | arr[i] = rArr[r] 20 | r += 1 21 | } else if r >= rArr.count { 22 | arr[i] = lArr[l] 23 | l += 1 24 | } else if isNotOrdered(lArr[l], rArr[r]) { 25 | arr[i] = lArr[l] 26 | l += 1 27 | } else { 28 | arr[i] = rArr[r] 29 | r += 1 30 | } 31 | } 32 | 33 | return arr 34 | } 35 | 36 | // guard arr.count > 1 else { return arr } 37 | // 当数组大小小于等于 15 时,切换为插入排序 38 | if arr.count <= 15 { 39 | return insertionSortAdvanced(arr, isNotOrdered) 40 | } 41 | 42 | let mid = arr.count / 2 43 | 44 | let lArr = mergeSortAdvanced(Array(arr[0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 57 | var arr = arr 58 | 59 | for i in 0.. 0 && isNotOrdered(e, arr[j - 1]) { 65 | arr[j] = arr[j - 1] 66 | j -= 1 67 | } 68 | arr[j] = e 69 | } 70 | 71 | return arr 72 | } 73 | 74 | TestHelper.checkSortAlgorithm(mergeSortAdvanced) 75 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(mergeSortAdvanced) 76 | -------------------------------------------------------------------------------- /Sort/07-MergeSort-Advanced/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func mergeSortAdvanced(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 9 | // [0, mid) & [mid, arr.count) 10 | func merge(_ lArr: Array, _ rArr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 11 | var arr = lArr + rArr 12 | var l = 0, r = 0 13 | 14 | for i in 0..= lArr.count { 16 | arr[i] = rArr[r] 17 | r += 1 18 | } else if r >= rArr.count { 19 | arr[i] = lArr[l] 20 | l += 1 21 | } else if isNotOrdered(lArr[l], rArr[r]) { 22 | arr[i] = lArr[l] 23 | l += 1 24 | } else { 25 | arr[i] = rArr[r] 26 | r += 1 27 | } 28 | } 29 | 30 | return arr 31 | } 32 | 33 | // guard arr.count > 1 else { return arr } 34 | // 当数组大小小于等于 15 时,切换为插入排序 35 | if arr.count <= 15 { 36 | return insertionSortAdvanced(arr, isNotOrdered) 37 | } 38 | 39 | let mid = arr.count / 2 40 | 41 | let lArr = mergeSortAdvanced(Array(arr[0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 54 | var arr = arr 55 | 56 | for i in 0.. 0 && isNotOrdered(e, arr[j - 1]) { 62 | arr[j] = arr[j - 1] 63 | j -= 1 64 | } 65 | arr[j] = e 66 | } 67 | 68 | return arr 69 | } 70 | ``` 71 | 72 | ## License 73 | 74 | MIT 75 | -------------------------------------------------------------------------------- /Sort/08-MergeSort-BottomUp/08-MergeSort-BottomUp.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/08-MergeSort-BottomUp/08-MergeSort-BottomUp/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 12 | // [l, mid) & [mid, r) 13 | func merge(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ mid: Int, _ r: Int) { 14 | let tmpArr = arr 15 | var leftIndex = l, rightIndex = mid 16 | 17 | for i in 0..= mid { 19 | arr[i + l] = tmpArr[rightIndex] 20 | rightIndex += 1 21 | } else if rightIndex >= r { 22 | arr[i + l] = tmpArr[leftIndex] 23 | leftIndex += 1 24 | } else if isNotOrdered(tmpArr[leftIndex], tmpArr[rightIndex]) { 25 | arr[i + l] = tmpArr[leftIndex] 26 | leftIndex += 1 27 | } else { 28 | arr[i + l] = tmpArr[rightIndex] 29 | rightIndex += 1 30 | } 31 | } 32 | } 33 | 34 | var arr = arr 35 | 36 | var size = 1 37 | while size <= arr.count { 38 | var i = 0 39 | while i + size < arr.count { 40 | merge(&arr, isNotOrdered, i, size + i, min(i + size + size, arr.count)) 41 | i += (size + size) 42 | } 43 | size += size 44 | } 45 | 46 | return arr 47 | } 48 | 49 | func mergeSortBottomUpWithInsertionSort(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 50 | // [l, mid) & [mid, r) 51 | func merge(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ mid: Int, _ r: Int) { 52 | if r - l <= 15 { 53 | arr = insertionSortAdvanced(arr, isNotOrdered, l, r) 54 | return 55 | } 56 | 57 | let tmpArr = arr 58 | var leftIndex = l, rightIndex = mid 59 | 60 | for i in 0..= mid { 62 | arr[i + l] = tmpArr[rightIndex] 63 | rightIndex += 1 64 | } else if rightIndex >= r { 65 | arr[i + l] = tmpArr[leftIndex] 66 | leftIndex += 1 67 | } else if isNotOrdered(tmpArr[leftIndex], tmpArr[rightIndex]) { 68 | arr[i + l] = tmpArr[leftIndex] 69 | leftIndex += 1 70 | } else { 71 | arr[i + l] = tmpArr[rightIndex] 72 | rightIndex += 1 73 | } 74 | } 75 | } 76 | 77 | var arr = arr 78 | 79 | var size = 1 80 | while size <= arr.count { 81 | var i = 0 82 | while i + size < arr.count { 83 | merge(&arr, isNotOrdered, i, size + i, min(i + size + size, arr.count)) 84 | i += (size + size) 85 | } 86 | size += size 87 | } 88 | 89 | return arr 90 | } 91 | 92 | func insertionSortAdvanced(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> Array { 93 | var arr = arr 94 | 95 | for i in l.. l && isNotOrdered(e, arr[j - 1]) { 101 | arr[j] = arr[j - 1] 102 | j -= 1 103 | } 104 | arr[j] = e 105 | } 106 | 107 | return arr 108 | } 109 | 110 | TestHelper.checkSortAlgorithm(mergeSortBottomUp) 111 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(mergeSortBottomUp) 112 | 113 | TestHelper.checkSortAlgorithm(mergeSortBottomUpWithInsertionSort) 114 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(mergeSortBottomUpWithInsertionSort) 115 | -------------------------------------------------------------------------------- /Sort/08-MergeSort-BottomUp/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func mergeSortBottomUp(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 9 | // [l, mid) & [mid, r) 10 | func merge(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ mid: Int, _ r: Int) { 11 | let tmpArr = arr 12 | var leftIndex = l, rightIndex = mid 13 | 14 | for i in 0..= mid { 16 | arr[i + l] = tmpArr[rightIndex] 17 | rightIndex += 1 18 | } else if rightIndex >= r { 19 | arr[i + l] = tmpArr[leftIndex] 20 | leftIndex += 1 21 | } else if isNotOrdered(tmpArr[leftIndex], tmpArr[rightIndex]) { 22 | arr[i + l] = tmpArr[leftIndex] 23 | leftIndex += 1 24 | } else { 25 | arr[i + l] = tmpArr[rightIndex] 26 | rightIndex += 1 27 | } 28 | } 29 | } 30 | 31 | var arr = arr 32 | 33 | var size = 1 34 | while size <= arr.count { 35 | var i = 0 36 | while i + size < arr.count { 37 | merge(&arr, isNotOrdered, i, size + i, min(i + size + size, arr.count)) 38 | i += (size + size) 39 | } 40 | size += size 41 | } 42 | 43 | return arr 44 | } 45 | 46 | func mergeSortBottomUpWithInsertionSort(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 47 | // [l, mid) & [mid, r) 48 | func merge(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ mid: Int, _ r: Int) { 49 | if r - l <= 15 { 50 | arr = insertionSortAdvanced(arr, isNotOrdered, l, r) 51 | return 52 | } 53 | 54 | let tmpArr = arr 55 | var leftIndex = l, rightIndex = mid 56 | 57 | for i in 0..= mid { 59 | arr[i + l] = tmpArr[rightIndex] 60 | rightIndex += 1 61 | } else if rightIndex >= r { 62 | arr[i + l] = tmpArr[leftIndex] 63 | leftIndex += 1 64 | } else if isNotOrdered(tmpArr[leftIndex], tmpArr[rightIndex]) { 65 | arr[i + l] = tmpArr[leftIndex] 66 | leftIndex += 1 67 | } else { 68 | arr[i + l] = tmpArr[rightIndex] 69 | rightIndex += 1 70 | } 71 | } 72 | } 73 | 74 | var arr = arr 75 | 76 | var size = 1 77 | while size <= arr.count { 78 | var i = 0 79 | while i + size < arr.count { 80 | merge(&arr, isNotOrdered, i, size + i, min(i + size + size, arr.count)) 81 | i += (size + size) 82 | } 83 | size += size 84 | } 85 | 86 | return arr 87 | } 88 | 89 | func insertionSortAdvanced(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> Array { 90 | var arr = arr 91 | 92 | for i in l.. l && isNotOrdered(e, arr[j - 1]) { 98 | arr[j] = arr[j - 1] 99 | j -= 1 100 | } 101 | arr[j] = e 102 | } 103 | 104 | return arr 105 | } 106 | ``` 107 | 108 | ## License 109 | 110 | MIT 111 | -------------------------------------------------------------------------------- /Sort/09-QuickSort/09-QuickSort.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/09-QuickSort/09-QuickSort/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 12 | func partition(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> (index: Int, array: Array) { 13 | var arr = arr 14 | let tmp = arr[l] 15 | 16 | var j = l 17 | for i in (l + 1).. 1 else { return arr } 33 | 34 | let res = partition(arr, isNotOrdered, 0, arr.count) 35 | let lArr = quickSort(Array(res.array[0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 9 | func partition(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> (index: Int, array: Array) { 10 | var arr = arr 11 | let tmp = arr[l] 12 | 13 | var j = l 14 | for i in (l + 1).. 1 else { return arr } 30 | 31 | let res = partition(arr, isNotOrdered, 0, arr.count) 32 | let lArr = quickSort(Array(res.array[0.. 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/10-QuickSort-Randomized/10-QuickSort-Randomized/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 12 | func partition(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> (index: Int, array: Array) { 13 | var arr = arr 14 | // 随机化索引 [l, r) 15 | let tmpIndex = Int(arc4random_uniform(UInt32(r - l))) + l 16 | if l != tmpIndex { 17 | swap(&arr[l], &arr[tmpIndex]) 18 | } 19 | 20 | let tmp = arr[l] 21 | 22 | var j = l 23 | for i in (l + 1).. 1 else { return arr } 39 | // 当数组大小小于等于 15 时,切换为插入排序 40 | if arr.count <= 15 { 41 | return insertionSortAdvanced(arr, isNotOrdered) 42 | } 43 | 44 | let res = partition(arr, isNotOrdered, 0, arr.count) 45 | let lArr = quickSortRandomized(Array(res.array[0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 53 | var arr = arr 54 | 55 | for i in 0.. 0 && isNotOrdered(e, arr[j - 1]) { 61 | arr[j] = arr[j - 1] 62 | j -= 1 63 | } 64 | arr[j] = e 65 | } 66 | 67 | return arr 68 | } 69 | 70 | TestHelper.checkSortAlgorithm(quickSortRandomized) 71 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(quickSortRandomized, 10000) 72 | -------------------------------------------------------------------------------- /Sort/10-QuickSort-Randomized/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func quickSortRandomized(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 9 | func partition(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> (index: Int, array: Array) { 10 | var arr = arr 11 | // 随机化索引 [l, r) 12 | let tmpIndex = Int(arc4random_uniform(UInt32(r - l))) + l 13 | if l != tmpIndex { 14 | swap(&arr[l], &arr[tmpIndex]) 15 | } 16 | 17 | let tmp = arr[l] 18 | 19 | var j = l 20 | for i in (l + 1).. 1 else { return arr } 36 | // 当数组大小小于等于 15 时,切换为插入排序 37 | if arr.count <= 15 { 38 | return insertionSortAdvanced(arr, isNotOrdered) 39 | } 40 | 41 | let res = partition(arr, isNotOrdered, 0, arr.count) 42 | let lArr = quickSortRandomized(Array(res.array[0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 50 | var arr = arr 51 | 52 | for i in 0.. 0 && isNotOrdered(e, arr[j - 1]) { 58 | arr[j] = arr[j - 1] 59 | j -= 1 60 | } 61 | arr[j] = e 62 | } 63 | 64 | return arr 65 | } 66 | ``` 67 | 68 | ## License 69 | 70 | MIT 71 | -------------------------------------------------------------------------------- /Sort/11-QuickSort-2-Way/11-QuickSort-2-Way.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/11-QuickSort-2-Way/11-QuickSort-2-Way/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 12 | func partition(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> (index: Int, array: Array) { 13 | var arr = arr 14 | // 随机化索引 [l, r) 15 | let tmpIndex = Int(arc4random_uniform(UInt32(r - l))) + l 16 | if l != tmpIndex { 17 | swap(&arr[l], &arr[tmpIndex]) 18 | } 19 | let tmp = arr[l] 20 | 21 | // [l + 1, r - 1] 22 | var i = l + 1, j = r - 1 23 | while true { 24 | while i <= r - 1 && isNotOrdered(arr[i], tmp) { 25 | i += 1 26 | } 27 | while j >= l + 1 && isNotOrdered(tmp, arr[j]) { 28 | j -= 1 29 | } 30 | 31 | if i > j { 32 | break 33 | } 34 | 35 | if i != j { 36 | swap(&arr[i], &arr[j]) 37 | } 38 | 39 | i += 1 40 | j -= 1 41 | } 42 | 43 | if l != j { 44 | swap(&arr[l], &arr[j]) 45 | } 46 | return (j, arr) 47 | } 48 | 49 | // guard arr.count > 1 else { return arr } 50 | // 当数组大小小于等于 15 时,切换为插入排序 51 | if arr.count <= 15 { 52 | return insertionSortAdvanced(arr, isNotOrdered) 53 | } 54 | 55 | let res = partition(arr, isNotOrdered, 0, arr.count) 56 | let lArr = quickSortTwoWay(Array(res.array[0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 64 | var arr = arr 65 | 66 | for i in 0.. 0 && isNotOrdered(e, arr[j - 1]) { 72 | arr[j] = arr[j - 1] 73 | j -= 1 74 | } 75 | arr[j] = e 76 | } 77 | 78 | return arr 79 | } 80 | 81 | TestHelper.checkSortAlgorithm(quickSortTwoWay, 10000) 82 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(quickSortTwoWay, 10000) 83 | TestHelper.checkSortAlgorithmWithArrayInGivenRange(quickSortTwoWay, 0, 5, 10000) 84 | -------------------------------------------------------------------------------- /Sort/11-QuickSort-2-Way/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func quickSortTwoWay(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 9 | func partition(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> (index: Int, array: Array) { 10 | var arr = arr 11 | // 随机化索引 [l, r) 12 | let tmpIndex = Int(arc4random_uniform(UInt32(r - l))) + l 13 | if l != tmpIndex { 14 | swap(&arr[l], &arr[tmpIndex]) 15 | } 16 | let tmp = arr[l] 17 | 18 | // [l + 1, r - 1] 19 | var i = l + 1, j = r - 1 20 | while true { 21 | while i <= r - 1 && isNotOrdered(arr[i], tmp) { 22 | i += 1 23 | } 24 | while j >= l + 1 && isNotOrdered(tmp, arr[j]) { 25 | j -= 1 26 | } 27 | 28 | if i > j { 29 | break 30 | } 31 | 32 | if i != j { 33 | swap(&arr[i], &arr[j]) 34 | } 35 | 36 | i += 1 37 | j -= 1 38 | } 39 | 40 | if l != j { 41 | swap(&arr[l], &arr[j]) 42 | } 43 | return (j, arr) 44 | } 45 | 46 | // guard arr.count > 1 else { return arr } 47 | // 当数组大小小于等于 15 时,切换为插入排序 48 | if arr.count <= 15 { 49 | return insertionSortAdvanced(arr, isNotOrdered) 50 | } 51 | 52 | let res = partition(arr, isNotOrdered, 0, arr.count) 53 | let lArr = quickSortTwoWay(Array(res.array[0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 61 | var arr = arr 62 | 63 | for i in 0.. 0 && isNotOrdered(e, arr[j - 1]) { 69 | arr[j] = arr[j - 1] 70 | j -= 1 71 | } 72 | arr[j] = e 73 | } 74 | 75 | return arr 76 | } 77 | ``` 78 | 79 | ## License 80 | 81 | MIT 82 | -------------------------------------------------------------------------------- /Sort/12-QuickSort-3-Way/12-QuickSort-3-Way.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/12-QuickSort-3-Way/12-QuickSort-3-Way/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 12 | func partition(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) { 13 | if r - l <= 15 { 14 | arr = insertionSortAdvanced(arr, isNotOrdered, l, r) 15 | return 16 | } 17 | // guard r - l > 1 else { return } 18 | 19 | // 随机化索引 [l, r) 20 | let tmpIndex = Int(arc4random_uniform(UInt32(r - l))) + l 21 | if l != tmpIndex { 22 | swap(&arr[l], &arr[tmpIndex]) 23 | } 24 | let tmp = arr[l] 25 | 26 | // [l + 1, r - 1] 27 | var lt = l, gt = r, i = l + 1 28 | while i < gt { 29 | if isNotOrdered(arr[i], tmp) { 30 | if i != lt + 1 { 31 | swap(&arr[i], &arr[lt + 1]) 32 | } 33 | lt += 1 34 | i += 1 35 | } else if isNotOrdered(tmp, arr[i]) { 36 | if i != gt - 1 { 37 | swap(&arr[i], &arr[gt - 1]) 38 | } 39 | gt -= 1 40 | } else { 41 | i += 1 42 | } 43 | } 44 | 45 | if l != lt { 46 | swap(&arr[l], &arr[lt]) 47 | } 48 | 49 | partition(&arr, isNotOrdered, l, lt) 50 | partition(&arr, isNotOrdered, gt - 1, r) 51 | } 52 | 53 | var arr = arr 54 | partition(&arr, isNotOrdered, 0, arr.count) 55 | return arr 56 | } 57 | 58 | func insertionSortAdvanced(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> Array { 59 | var arr = arr 60 | 61 | for i in l.. l && isNotOrdered(e, arr[j - 1]) { 67 | arr[j] = arr[j - 1] 68 | j -= 1 69 | } 70 | arr[j] = e 71 | } 72 | 73 | return arr 74 | } 75 | 76 | TestHelper.checkSortAlgorithm(quickSortThreeWay, 10000) 77 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(quickSortThreeWay, 10000) 78 | TestHelper.checkSortAlgorithmWithArrayInGivenRange(quickSortThreeWay, 0, 5, 10000) 79 | -------------------------------------------------------------------------------- /Sort/12-QuickSort-3-Way/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func quickSortThreeWay(_ arr: Array, _ isNotOrdered: (T, T) -> Bool) -> Array { 9 | func partition(_ arr: inout Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) { 10 | if r - l <= 15 { 11 | arr = insertionSortAdvanced(arr, isNotOrdered, l, r) 12 | return 13 | } 14 | // guard r - l > 1 else { return } 15 | 16 | // 随机化索引 [l, r) 17 | let tmpIndex = Int(arc4random_uniform(UInt32(r - l))) + l 18 | if l != tmpIndex { 19 | swap(&arr[l], &arr[tmpIndex]) 20 | } 21 | let tmp = arr[l] 22 | 23 | // [l + 1, r - 1] 24 | var lt = l, gt = r, i = l + 1 25 | while i < gt { 26 | if isNotOrdered(arr[i], tmp) { 27 | if i != lt + 1 { 28 | swap(&arr[i], &arr[lt + 1]) 29 | } 30 | lt += 1 31 | i += 1 32 | } else if isNotOrdered(tmp, arr[i]) { 33 | if i != gt - 1 { 34 | swap(&arr[i], &arr[gt - 1]) 35 | } 36 | gt -= 1 37 | } else { 38 | i += 1 39 | } 40 | } 41 | 42 | if l != lt { 43 | swap(&arr[l], &arr[lt]) 44 | } 45 | 46 | partition(&arr, isNotOrdered, l, lt) 47 | partition(&arr, isNotOrdered, gt - 1, r) 48 | } 49 | 50 | var arr = arr 51 | partition(&arr, isNotOrdered, 0, arr.count) 52 | return arr 53 | } 54 | 55 | func insertionSortAdvanced(_ arr: Array, _ isNotOrdered: (T, T) -> Bool, _ l: Int, _ r: Int) -> Array { 56 | var arr = arr 57 | 58 | for i in l.. l && isNotOrdered(e, arr[j - 1]) { 64 | arr[j] = arr[j - 1] 65 | j -= 1 66 | } 67 | arr[j] = e 68 | } 69 | 70 | return arr 71 | } 72 | ``` 73 | 74 | ## License 75 | 76 | MIT 77 | -------------------------------------------------------------------------------- /Sort/13-HeapSort/13-HeapSort.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/13-HeapSort/13-HeapSort/Heap.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Heap.swift 3 | // 01-Heap 4 | // 5 | // Created by 买明 on 21/03/2017. 6 | // Copyright © 2017 买明. All rights reserved. 7 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 8 | 9 | import Foundation 10 | 11 | public struct Heap: CustomStringConvertible { 12 | 13 | var isOrdered: (T, T) -> Bool 14 | var capacity: Int 15 | 16 | var elements: Array 17 | 18 | var count: Int { 19 | return elements.count 20 | } 21 | var isEmpty: Bool { 22 | return elements.isEmpty 23 | } 24 | 25 | public var description: String { 26 | return elements.description 27 | } 28 | 29 | init(_ capacity: Int, _ isOrdered: @escaping (T, T) -> Bool) { 30 | self.capacity = capacity 31 | self.isOrdered = isOrdered 32 | self.elements = Array() 33 | } 34 | 35 | private mutating func shiftUp(_ index: Int) { 36 | var index = index 37 | while index > 0 && isOrdered(elements[index], elements[(index - 1) / 2]) { 38 | swap(&elements[index], &elements[(index - 1) / 2]) 39 | index = (index - 1) / 2 40 | } 41 | } 42 | 43 | private mutating func shiftDown(_ index: Int) { 44 | var index = index 45 | while 2 * (index + 1) <= count { 46 | var j = 2 * index + 1 47 | if j + 1 < count && isOrdered(elements[j + 1], elements[j]) { 48 | j += 1 49 | } 50 | 51 | if isOrdered(elements[j], elements[index]) { 52 | swap(&elements[j], &elements[index]) 53 | } 54 | index = j 55 | } 56 | } 57 | 58 | mutating func insert(_ element: T) { 59 | assert(count + 1 <= capacity, "Heap out of capacity.") 60 | elements.append(element) 61 | shiftUp(count - 1) 62 | } 63 | 64 | mutating func extractExtremum() -> T { 65 | assert(!isEmpty, "Heap is Empty") 66 | let returnElement = elements[0] 67 | if count > 1 { 68 | swap(&elements[0], &elements[count - 1]) 69 | } 70 | elements.removeLast() 71 | shiftDown(0) 72 | return returnElement 73 | } 74 | 75 | public func getExtremum() -> T { 76 | assert(!isEmpty, "Heap is Empty") 77 | return elements[0] 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /Sort/13-HeapSort/13-HeapSort/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0..(_ arr: Array, _ isNotOrdered: @escaping (T, T) -> Bool) -> Array { 12 | var heap = Heap(arr.count, isNotOrdered) 13 | for i in arr { 14 | heap.insert(i) 15 | } 16 | var result = Array() 17 | for _ in arr { 18 | result.append(heap.extractExtremum()) 19 | } 20 | 21 | return result 22 | } 23 | 24 | TestHelper.checkSortAlgorithm(heapSort) 25 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(heapSort) 26 | TestHelper.checkSortAlgorithmWithArrayInGivenRange(heapSort, 1, 10) 27 | -------------------------------------------------------------------------------- /Sort/13-HeapSort/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | func heapSort(_ arr: Array, _ isNotOrdered: @escaping (T, T) -> Bool) -> Array { 9 | var heap = Heap(arr.count, isNotOrdered) 10 | for i in arr { 11 | heap.insert(i) 12 | } 13 | var result = Array() 14 | for _ in arr { 15 | result.append(heap.extractExtremum()) 16 | } 17 | 18 | return result 19 | } 20 | ``` 21 | 22 | ## License 23 | 24 | MIT 25 | -------------------------------------------------------------------------------- /Sort/14-HeapSort-Heapify/14-HeapSort-Heapify.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Sort/14-HeapSort-Heapify/14-HeapSort-Heapify/Heap.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Heap.swift 3 | // 01-Heap 4 | // 5 | // Created by 买明 on 21/03/2017. 6 | // Copyright © 2017 买明. All rights reserved. 7 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 8 | 9 | import Foundation 10 | 11 | public struct Heap: CustomStringConvertible { 12 | 13 | var isOrdered: (T, T) -> Bool 14 | var capacity: Int 15 | 16 | var elements: Array 17 | 18 | var count: Int { 19 | return elements.count 20 | } 21 | var isEmpty: Bool { 22 | return elements.isEmpty 23 | } 24 | 25 | public var description: String { 26 | return elements.description 27 | } 28 | 29 | init(_ capacity: Int, _ isOrdered: @escaping (T, T) -> Bool) { 30 | self.capacity = capacity 31 | self.isOrdered = isOrdered 32 | self.elements = Array() 33 | } 34 | 35 | // init(_ array: Array, _ isOrdered: @escaping (T, T) -> Bool) { 36 | // self.capacity = array.count 37 | // self.isOrdered = isOrdered 38 | // self.elements = array 39 | // 40 | // for i in stride(from: (count - 2) / 2, through: 0, by: -1) { 41 | // shiftDown(i) 42 | // } 43 | // } 44 | 45 | private mutating func shiftUp(_ index: Int) { 46 | var index = index 47 | while index > 0 && isOrdered(elements[index], elements[(index - 1) / 2]) { 48 | swap(&elements[index], &elements[(index - 1) / 2]) 49 | index = (index - 1) / 2 50 | } 51 | } 52 | 53 | mutating func shiftDown(_ index: Int) { 54 | var index = index 55 | while 2 * (index + 1) <= count { 56 | var j = 2 * index + 1 57 | if j + 1 < count && isOrdered(elements[j + 1], elements[j]) { 58 | j += 1 59 | } 60 | 61 | if isOrdered(elements[j], elements[index]) { 62 | swap(&elements[j], &elements[index]) 63 | } 64 | index = j 65 | } 66 | } 67 | 68 | mutating func insert(_ element: T) { 69 | assert(count + 1 <= capacity, "Heap out of capacity.") 70 | elements.append(element) 71 | shiftUp(count - 1) 72 | } 73 | 74 | mutating func extractExtremum() -> T { 75 | assert(!isEmpty, "Heap is Empty") 76 | let returnElement = elements[0] 77 | if count > 1 { 78 | swap(&elements[0], &elements[count - 1]) 79 | } 80 | elements.removeLast() 81 | shiftDown(0) 82 | return returnElement 83 | } 84 | 85 | public func getExtremum() -> T { 86 | assert(!isEmpty, "Heap is Empty") 87 | return elements[0] 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /Sort/14-HeapSort-Heapify/14-HeapSort-Heapify/TestHelper.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestHelper.swift 3 | // 4 | // Created by 买明 on 10/03/2017. 5 | // Copyright © 2017 买明. All rights reserved. 6 | // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms 7 | 8 | import Foundation 9 | 10 | // 排序算法测试 11 | struct TestHelper { 12 | typealias SortFuncType = (inout Array, (Int, Int) -> Bool) -> () 13 | 14 | // 检查排序算法运行是否成功及耗时 15 | static func checkSortAlgorithm(_ sortFunction: (SortFuncType), 16 | _ arraySize: Int = 1000) { 17 | var array = generateRandomArray(arraySize) 18 | let startTime = clock() 19 | sortFunction(&array, <) 20 | let endTime = clock() 21 | if isSorted(array, <) { 22 | print("Duration: \(Double(endTime - startTime) / Double(CLOCKS_PER_SEC))s") 23 | } 24 | } 25 | 26 | // MARK: Private funcs 27 | 28 | // 返回随机整型数组 29 | private static func generateRandomArray(_ size: Int) -> Array { 30 | var resultArray = Array() 31 | 32 | for _ in 0..(_ array: [T], 40 | _ isOrdered: (T, T) -> Bool) -> Bool { 41 | guard array.count > 1 else { 42 | return true 43 | } 44 | 45 | for index in 0.., _ isOrdered: @escaping (T, T) -> Bool) { 13 | self.capacity = array.count 14 | self.isOrdered = isOrdered 15 | self.elements = array 16 | 17 | for i in stride(from: (count - 2) / 2, through: 0, by: -1) { 18 | shiftDown(i) 19 | } 20 | } 21 | } 22 | 23 | func heapSortHeapify(_ arr: Array, _ isNotOrdered: @escaping (T, T) -> Bool) -> Array { 24 | var heap = Heap(arr, isNotOrdered) 25 | var result = Array() 26 | for _ in arr { 27 | result.append(heap.extractExtremum()) 28 | } 29 | 30 | return result 31 | } 32 | 33 | TestHelper.checkSortAlgorithm(heapSortHeapify) 34 | TestHelper.checkSortAlgorithmWithNearlyOrderedArray(heapSortHeapify) 35 | TestHelper.checkSortAlgorithmWithArrayInGivenRange(heapSortHeapify, 1, 10) 36 | -------------------------------------------------------------------------------- /Sort/14-HeapSort-Heapify/README.md: -------------------------------------------------------------------------------- 1 | # Swift-X-Algorithms 2 | 3 | Algorithms implemented in Swift 4 | 5 | ## Code 6 | 7 | ```Swift 8 | extension Heap { 9 | init(_ array: Array, _ isOrdered: @escaping (T, T) -> Bool) { 10 | self.capacity = array.count 11 | self.isOrdered = isOrdered 12 | self.elements = array 13 | 14 | for i in stride(from: (count - 2) / 2, through: 0, by: -1) { 15 | shiftDown(i) 16 | } 17 | } 18 | } 19 | 20 | func heapSortHeapify(_ arr: Array, _ isNotOrdered: @escaping (T, T) -> Bool) -> Array { 21 | var heap = Heap(arr, isNotOrdered) 22 | var result = Array() 23 | for _ in arr { 24 | result.append(heap.extractExtremum()) 25 | } 26 | 27 | return result 28 | } 29 | ``` 30 | 31 | ## License 32 | 33 | MIT 34 | --------------------------------------------------------------------------------