28 | *
29 | * @apiNote - False positive if value not found in array (Returns -1)
30 | */
31 | @Test
32 | void testBinarySearchAssertNotEquals() {
33 |
34 | int targetNumber = 22; // Targeted number to get index
35 | boolean targetBoundary = false;
36 |
37 | // Int array
38 | int[] numArr = {2, 4, 8, 13, 14, 17, 19, 22, 22, 23, 25, 30, 32, 34, 35, 36, 38, 41, 44, 45, 46, 49};
39 |
40 | // Boolean array
41 | boolean[] boolArray = new boolean[]{false, false, false, true, true};
42 |
43 | String message = "Binary search should return index >= 0 from integer array";
44 |
45 | // Binary search in array
46 | assertNotEquals(-1, BinarySearch.binarySearch(numArr, targetNumber), () -> message);
47 |
48 | // Find boolean boundary from boolean array
49 | assertNotEquals(-1, BinarySearch.findBooleanBoundary(boolArray, targetBoundary), () -> message);
50 |
51 | // Find first element not smaller than target
52 | assertNotEquals(-1, BinarySearch.findFirstElementNotSmallerThanTarget(numArr,
53 | targetNumber), () -> message);
54 |
55 | // Find first target's occurrence in int array
56 | assertNotEquals(-1, BinarySearch.findFirstOccurrence(numArr, targetNumber), () -> message);
57 |
58 | // Calculate square root
59 | assertNotEquals(-1, BinarySearch.calculateSquareRoot(81), () -> message);
60 |
61 | // Find minimum in rotated sorted array
62 | assertNotEquals(-1, BinarySearch.findMinInRotatedArray(numArr));
63 |
64 | // Find the peak of the mountain
65 | assertNotEquals(-1, BinarySearch.findThePeakOfTheMountains(new int[]{0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0}));
66 | }
67 | }
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ "master" ]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [ "master" ]
20 | schedule:
21 | - cron: '37 8 * * 3'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: [ 'java' ]
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
38 |
39 | steps:
40 | - name: Checkout repository
41 | uses: actions/checkout@v3
42 |
43 | # Initializes the CodeQL tools for scanning.
44 | - name: Initialize CodeQL
45 | uses: github/codeql-action/init@v2
46 | with:
47 | languages: ${{ matrix.language }}
48 | # If you wish to specify custom queries, you can do so here or in a config file.
49 | # By default, queries listed here will override any specified in a config file.
50 | # Prefix the list here with "+" to use these queries and those in the config file.
51 |
52 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
53 | # queries: security-extended,security-and-quality
54 |
55 |
56 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
57 | # If this step fails, then you should remove it and run the build manually (see below)
58 | - name: Autobuild
59 | uses: github/codeql-action/autobuild@v2
60 |
61 | # ℹ️ Command-line programs to run using the OS shell.
62 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
63 |
64 | # If the Autobuild fails above, remove it and uncomment the following three lines.
65 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
66 |
67 | # - run: |
68 | # echo "Run, Build Application using script"
69 | # ./location_of_script_within_repo/buildscript.sh
70 |
71 | - name: Perform CodeQL Analysis
72 | uses: github/codeql-action/analyze@v2
73 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/.github/workflows/crda.yml:
--------------------------------------------------------------------------------
1 | # This workflow uses actions that are not certified by GitHub.
2 | # They are provided by a third-party and are governed by
3 | # separate terms of service, privacy policy, and support
4 | # documentation.
5 |
6 | # This workflow performs a static analysis of your source code using
7 | # Red Hat CodeReady Dependency Analytics.
8 |
9 | # Scans are triggered:
10 | # 1. On every push to default and protected branches
11 | # 2. On every Pull Request targeting the default branch
12 | # 3. On a weekly schedule
13 | # 4. Manually, on demand, via the "workflow_dispatch" event
14 |
15 | # 💁 The CRDA Starter workflow will:
16 | # - Checkout your repository
17 | # - Setup the required tool stack
18 | # - Install the CRDA command line tool
19 | # - Auto detect the manifest file and install the project's dependencies
20 | # - Perform the security scan using CRDA
21 | # - Upload the SARIF result to the GitHub Code Scanning which can be viewed under the security tab
22 | # - Optionally upload the SARIF file as an artifact for the future reference
23 |
24 | # ℹ️ Configure your repository and the workflow with the following steps:
25 | # 1. Setup the tool stack based on the project's requirement.
26 | # Refer to: https://github.com/redhat-actions/crda/#1-set-up-the-tool-stack
27 | # 2. (Optional) CRDA action attempt to detect the language and install the
28 | # required dependencies for your project. If your project doesn't aligns
29 | # with the default dependency installation command mentioned here
30 | # https://github.com/redhat-actions/crda/#3-installing-dependencies.
31 | # Use the required inputs to setup the same
32 | # 3. (Optional) CRDA action attempts to detect the manifest file if it is
33 | # present in the root of the project and named as per the default mentioned
34 | # here https://github.com/redhat-actions/crda/#3-installing-dependencies.
35 | # If it deviates from the default, use the required inputs to setup the same
36 | # 4. Setup Authentication - Create the CRDA_KEY or SNYK_TOKEN.
37 | # Refer to: https://github.com/redhat-actions/crda/#4-set-up-authentication
38 | # 5. (Optional) Upload SARIF file as an Artifact to download and view
39 | # 6. Commit and push the workflow file to your default branch to trigger a workflow run.
40 |
41 | # 👋 Visit our GitHub organization at https://github.com/redhat-actions/ to see our actions and provide feedback.
42 |
43 | name: CRDA Scan
44 |
45 | # Controls when the workflow will run
46 | on:
47 | # TODO: Customize trigger events based on your DevSecOps processes
48 | #
49 | # This workflow is made to run with OpenShift starter workflow
50 | # https://github.com/actions/starter-workflows/blob/main/deployments/openshift.yml
51 | # However, if you want to run this workflow as a standalone workflow, please
52 | # uncomment the 'push' trigger below and configure it based on your requirements.
53 | #
54 | workflow_call:
55 | secrets:
56 | CRDA_KEY:
57 | required: false
58 | SNYK_TOKEN:
59 | required: false
60 | workflow_dispatch:
61 |
62 | # push:
63 | # branches: [ "master" ]
64 |
65 | # pull_request_target is used to securely share secret to the PR's workflow run.
66 | # For more info visit: https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target
67 | pull_request_target:
68 | branches: [ "master" ]
69 | types: [ assigned, opened, synchronize, reopened, labeled, edited ]
70 |
71 | permissions:
72 | contents: read
73 |
74 | jobs:
75 | crda-scan:
76 | permissions:
77 | contents: read # for actions/checkout to fetch code
78 | security-events: write # for redhat-actions/crda to upload SARIF results
79 | name: Scan project vulnerabilities with CRDA
80 | runs-on: ubuntu-20.04
81 | steps:
82 |
83 | - name: Check out repository
84 | uses: actions/checkout@v2
85 |
86 | # *******************************************************************
87 | # Required: Instructions to setup project
88 | # 1. Setup Go, Java, Node.js or Python depending on your project type
89 | # 2. Setup Actions are listed below, choose one from them:
90 | # - Go: https://github.com/actions/setup-go
91 | # - Java: https://github.com/actions/setup-java
92 | # - Node.js: https://github.com/actions/setup-node
93 | # - Python: https://github.com/actions/setup-python
94 | #
95 | # Example:
96 | # - name: Setup Node
97 | # uses: actions/setup-node@v2
98 | # with:
99 | # node-version: '14'
100 |
101 | # https://github.com/redhat-actions/openshift-tools-installer/blob/main/README.md
102 | - name: Install CRDA CLI
103 | uses: redhat-actions/openshift-tools-installer@v1
104 | with:
105 | source: github
106 | github_pat: ${{ github.token }}
107 | # Choose the desired version of the CRDA CLI
108 | crda: "latest"
109 |
110 | ######################################################################################
111 | # https://github.com/redhat-actions/crda/blob/main/README.md
112 | #
113 | # By default, CRDA will detect the manifest file and install the required dependencies
114 | # using the standard command for the project type.
115 | # If your project doesn't aligns with the defaults mentioned in this action, you will
116 | # need to set few inputs that are described here:
117 | # https://github.com/redhat-actions/crda/blob/main/README.md#3-installing-dependencies
118 | # Visit https://github.com/redhat-actions/crda/#4-set-up-authentication to understand
119 | # process to get a SNYK_TOKEN or a CRDA_KEY
120 | - name: CRDA Scan
121 | id: scan
122 | uses: redhat-actions/crda@v1
123 | with:
124 | crda_key: ${{ secrets.CRDA_KEY }} # Either use crda_key or snyk_token
125 | # snyk_token: ${{ secrets.SNYK_TOKEN }}
126 | # upload_artifact: false # Set this to false to skip artifact upload
127 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | -
6 |
7 |
8 | -
9 |
10 |
11 | -
12 |
13 |
14 | -
15 |
16 |
17 | -
18 |
19 |
20 |
21 |
22 |
23 | -
24 |
25 |
26 |
27 |
28 |
29 | -
30 |
31 |
32 |
33 |
34 |
35 | -
36 |
37 |
38 |
39 |
40 |
41 | -
42 |
43 |
44 |
45 |
46 | -
47 |
48 |
49 |
50 |
51 | -
52 |
53 |
54 |
55 |
56 | -
57 |
58 |
59 |
60 |
61 | -
62 |
63 |
64 |
65 |
66 | -
67 |
68 |
69 |
70 |
71 | -
72 |
73 |
74 | -
75 |
76 |
77 |
78 |
79 | -
80 |
81 |
82 |
83 |
84 | -
85 |
86 |
87 |
88 |
89 | -
90 |
91 |
92 |
93 |
94 | -
95 |
96 |
97 |
98 |
99 | -
100 |
101 |
102 | -
103 |
104 |
105 | -
106 |
107 |
108 | -
109 |
110 |
111 | -
112 |
113 |
114 |
115 |
116 | -
117 |
118 |
119 | -
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/src/main/java/binary_search/BinarySearch.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Class with BinarySearch code
3 | *
4 | * @author David Kariuki David Kariuki
5 | * @apiNote - Binary search example cases
6 | * @see #binarySearch(Type, Type)
7 | * @see #findBooleanBoundary(Type, Type)
8 | * @see #findFirstElementNotSmallerThanTarget(Type, Type)
9 | * @see #findFirstOccurrence(Type, Type)
10 | * @see #calculateSquareRoot(Type)
11 | * @see #findMinInRotatedArray(Type)
12 | * @see #findThePeakOfTheMountains(Type))
13 | * @since 14/7/2022
14 | */
15 |
16 | package binary_search;
17 |
18 | import utilities.SharedUtils;
19 |
20 | public class BinarySearch {
21 |
22 | private static int start = 0; // Set all arrays starting point
23 | private static int end = 0; // Set all arrays ending point before they are recalculated
24 |
25 | /**
26 | * Main method
27 | *
28 | * @param args - Arguments array
29 | */
30 | public static void main(String[] args) {
31 |
32 | // Shared values
33 | int[] intArr = {2, 4, 8, 13, 14, 14, 17, 19, 22, 23, 25, 30};
34 | int targetInt = 14; // Targeted number to get index
35 | boolean[] boolArray = new boolean[]{false, false, false, true, true};
36 | boolean targetBoolean = true;
37 | int index;
38 |
39 | // Binary search with in t array
40 | index = BinarySearch.binarySearch(intArr, targetInt); // Get target numbers index
41 | if (index != -1) {
42 | System.out.print("The target number : " + targetInt + " is at index (" + index + ")" + "\n\n\n");
43 | } else {
44 | System.out.println("The number : " + targetInt + " was not found in the int array" + "\n\n\n");
45 | }
46 |
47 |
48 | // Binary search with boolean array
49 | index = BinarySearch.findBooleanBoundary(boolArray, targetBoolean);
50 |
51 | if (index != -1) {
52 | System.out.print("The boolean boundary for the start of value : " + targetBoolean
53 | + " is at pos { " + index + " }" + "\n\n\n");
54 | } else {
55 | System.out.println("The boolean : " + targetBoolean + " was not found in the boolean array" + "\n\n\n");
56 | }
57 |
58 |
59 | // Get element not smaller than target
60 | index = BinarySearch.findFirstElementNotSmallerThanTarget(intArr, targetInt);
61 | if (index != -1) {
62 | System.out.print("The first element not smaller than the target number : " + targetInt
63 | + " is at index (" + index + ") and the number is : " + intArr[index] + "\n\n\n");
64 | } else {
65 | System.out.println("The number : " + targetInt + " was not found in the int array" + "\n\n\n");
66 | }
67 |
68 |
69 | // Get the first occurrence of an in t in an int array
70 | index = BinarySearch.findFirstOccurrence(intArr, targetInt);
71 | if (index != -1) {
72 | System.out.print("The first occurrence of the target number : " + targetInt
73 | + " is at index (" + index + ") and the number is : " + intArr[index] + "\n\n\n");
74 | } else {
75 | System.out.println("The number : " + targetInt + " was not found in the int array" + "\n\n\n");
76 | }
77 |
78 |
79 | // Get square root of a number
80 | int sqNum1 = 4;
81 | int sqNum2 = 8;
82 | int sqNum3 = 16;
83 | System.out.println("The square root of " + sqNum1 + " is : " + BinarySearch.calculateSquareRoot(sqNum1));
84 | System.out.println("The square root of " + sqNum2 + " is : " + BinarySearch.calculateSquareRoot(sqNum2));
85 | System.out.println("The square root of " + sqNum3 + " is : " + BinarySearch.calculateSquareRoot(sqNum3));
86 |
87 |
88 | // Get minimum in rotated sorted array
89 | System.out.println("Find minimum rotated :" + BinarySearch.findMinInRotatedArray(new int[]{30, 40, 50, 10, 20}));
90 | System.out.println("Find minimum rotated :" + BinarySearch.findMinInRotatedArray(new int[]{0, 1, 2, 3, 4, 5}));
91 | System.out.println("Find minimum rotated :" + BinarySearch.findMinInRotatedArray(new int[]{0}));
92 |
93 |
94 | // Get the peak of the mountain
95 | System.out.println("The peak of the Mountain is at : "
96 | + BinarySearch.findThePeakOfTheMountains(new int[]{0, 1, 2, 3, 4, 3, 2, 1, 0}));
97 | System.out.println("The peak of the Mountain is at : "
98 | + BinarySearch.findThePeakOfTheMountains(new int[]{4, 5, 6, 7, 8, 7, 6, 5, 4}));
99 |
100 | }
101 |
102 | /**
103 | * Method to perform binary search
104 | *
105 | * @param arr - int array
106 | * @param target - Target number to get index
107 | * @return int - Index/-1
108 | *
109 | *
110 | * PROBLEM STATEMENT
111 | * Given a sorted array of integers and an integer called target, find the element that equals the
112 | * target and return its index.
113 | */
114 | public static int binarySearch(final int[] arr, final int target) {
115 |
116 | end = SharedUtils.calculateArraysEndPoint(arr); // Get the end point of the array
117 |
118 | // Loop through array
119 | while (start <= end) {
120 | int mid = SharedUtils.calculateArraysMidPoint(start, end); // Calculate arrays mid point
121 |
122 | // Check if value at mid, equals to target and return
123 | if (arr[mid] == target) {
124 | return mid; // return numbers index
125 | }
126 |
127 | // Check if mid is less than target
128 | if (arr[mid] < target) {
129 | // Middle is less than the target, so discard left half by increasing start of search boundary
130 | start = mid + 1;
131 | }
132 |
133 | // Check if mid is greater that target
134 | if (arr[mid] > target) {
135 | // Middle is greater than the target, so discard right half by decreasing end of search boundary
136 | end = mid - 1;
137 | }
138 | }
139 |
140 | return -1;
141 | }
142 |
143 | /**
144 | * Method to find array boundary
145 | *
146 | * @param arr - Boolean array
147 | * @param target - Target boolean to get start index (Boundary)
148 | * @return int - Index(Boundary) / -1
149 | *
150 | *
151 | * PROBLEM STATEMENT
152 | * An array of boolean values is divided into two sections: the left section consists of all false,
153 | * and the right section consists of all true. Find the boundary of the right section,
154 | * i.e. the index of the first true element. If there is no true element, return -1.
155 | */
156 | public static int findBooleanBoundary(final boolean[] arr, final boolean target) {
157 |
158 | end = SharedUtils.calculateArraysEndPoint(arr); // Get arrays end point
159 | int boundaryIndex = -1; // Set initial boundary index
160 |
161 | // Loop through array
162 | while (start <= end) {
163 |
164 | int mid = SharedUtils.calculateArraysMidPoint(start, end); // Calculate arrays mid point
165 |
166 | // Check if the target value is at the current midpoint in loop
167 | if (arr[mid] == target) {
168 | boundaryIndex = mid;
169 | end = mid - 1;
170 | } else {
171 | start = mid + 1; // Move boundary forward
172 | }
173 | }
174 |
175 | return boundaryIndex;
176 | }
177 |
178 | /**
179 | * Method to get the index of the first element not smaller than target from an int array
180 | *
181 | * @param arr - int array
182 | * @param target - Targeted int
183 | * @return int - Index(Boundary) / -1
184 | *
185 | *
186 | * PROBLEM STATEMENT
187 | * Given an array of integers sorted in increasing order and a target, find the index of the first
188 | * element in the array that is larger or equal to the target. Assume that it is guaranteed to find
189 | * a satisfying number.
190 | */
191 | public static int findFirstElementNotSmallerThanTarget(final int[] arr, final int target) {
192 |
193 | end = SharedUtils.calculateArraysEndPoint(arr); // Get arrays end point
194 | int boundaryIndex = -1;
195 |
196 | // Loop through array
197 | while (start <= end) {
198 |
199 | int mid = SharedUtils.calculateArraysMidPoint(start, end); // Calculate arrays midpoint
200 |
201 | // Check if element at midpoint is greater or equal to target
202 | if (arr[mid] >= target) {
203 | boundaryIndex = mid;
204 | end = mid - 1;
205 | }
206 |
207 | // Check if element at midpoint is less than target
208 | if (arr[mid] < target) {
209 | start = mid + 1;
210 | }
211 | }
212 |
213 | return boundaryIndex;
214 | }
215 |
216 | /**
217 | * Method to get the first occurrence of a target in an int array
218 | *
219 | * @param arr - int array
220 | * @param target - Target number to get index
221 | * @return int - Index/-1
222 | *
223 | *
224 | * PROBLEM STATEMENT
225 | * Given a sorted array of integers and a target integer, find the first occurrence of
226 | * the target and return its index. Return -1 if the target is not in the array.
227 | */
228 | public static int findFirstOccurrence(final int[] arr, final int target) {
229 |
230 | end = SharedUtils.calculateArraysEndPoint(arr); // Get arrays end point
231 | int boundaryIndex = -1;
232 |
233 | while (start <= end) {
234 |
235 | // Calculate midpoint
236 | int mid = SharedUtils.calculateArraysMidPoint(start, end); // Calculate arrays midpoint
237 |
238 | // Check if midpoint is equal to target
239 | if (arr[mid] >= target) {
240 | boundaryIndex = mid;
241 | end = mid - 1;
242 | }
243 |
244 | // Check id value at midpoint is smaller than target
245 | if (arr[mid] < target) {
246 | start = mid + 1;
247 | }
248 | }
249 |
250 | return boundaryIndex;
251 | }
252 |
253 | /**
254 | * Method to find square root of an integer
255 | *
256 | * @param num - Integer to find square root of
257 | * @return -1 / Square root of integer
258 | *
259 | *
260 | * PROBLEM STATEMENT
261 | * Given an integer, find its square root without using the built-in square root function.
262 | * Only return the integer part (truncate the decimals).
263 | */
264 | public static int calculateSquareRoot(int num) {
265 |
266 | // Check if the number is 0
267 | if (num == 0) {
268 | return 0;
269 | } // return 0 for 0 value as square root of 0 is 0
270 |
271 | start = 1; // Set starting point
272 | end = num; // Set ending point
273 | int squareRoot = -1; // Initialized square root
274 |
275 | // Loop through boundary points
276 | while (start <= end) {
277 |
278 | int mid = SharedUtils.calculateArraysMidPoint(start, end); // Calculate arrays midpoint
279 |
280 | // Check if mid is less than or equal to division of number and midpoint
281 | if (mid <= (num / mid)) {
282 | squareRoot = mid;
283 | start = mid + 1;
284 | } else {
285 | end = mid - 1;
286 | }
287 | }
288 |
289 | return squareRoot;
290 | }
291 |
292 | /**
293 | * Method to find the minimum in rotated sorted array
294 | *
295 | * @param arr - int array
296 | * @return -1/index of minimum value
297 | *
298 | *
299 | * PROBLEM STATEMENT
300 | * A sorted array was rotated at an unknown pivot. For example,
301 | * [10, 20, 30, 40, 50] becomes [30, 40, 50, 10, 20]. Find the index of the minimum element in this array.
302 | */
303 | public static int findMinInRotatedArray(int[] arr) {
304 | start = 0;
305 | end = SharedUtils.calculateArraysEndPoint(arr); // Calculate array end point
306 | int boundaryIndex = -1; // Initialize boundary
307 |
308 | // Loop through the array
309 | while (start <= end) {
310 |
311 | int mid = SharedUtils.calculateArraysMidPoint(start, end); // Calculate arrays midpoint
312 |
313 | if (arr[mid] <= arr[SharedUtils.calculateArraysEndPoint(arr)]) {
314 | boundaryIndex = mid;
315 | end = mid - 1;
316 | } else {
317 | start = mid + 1;
318 | }
319 | }
320 |
321 | return boundaryIndex;
322 | }
323 |
324 | /**
325 | * Method to get the peak of the mountain
326 | *
327 | * @param arr - int array
328 | * @return -1 / peak of the mountain
329 | *
330 | *
331 | * PROBLEM STATEMENT
332 | * A mountain array is defined as an array that:
333 | * - Has at least 3 elements.
334 | * - Has an element with the largest value called the “peak”, at an index k. The array elements monotonically
335 | * increase from the first element to A[k], and then monotonically decreases from A[k + 1] to the last element
336 | * of the array. Thus creating a “mountain” of numbers.
337 | */
338 | public static int findThePeakOfTheMountains(int[] arr) {
339 |
340 | start = 0; // Set starting index
341 | end = SharedUtils.calculateArraysEndPoint(arr); // Get arrays end point
342 | int mountainPeak = -1; // Initialize peak
343 |
344 | // Loop through the array
345 | while (start <= end) {
346 |
347 | int mid = SharedUtils.calculateArraysMidPoint(start, end); // Calculate arrays midpoint
348 |
349 | if ((mid == SharedUtils.calculateArraysEndPoint(arr)) || (arr[mid] >= arr[mid + 1])) {
350 | mountainPeak = mid;
351 | end = mid - 1; // Set new end index
352 | } else {
353 | start = mid + 1; // Set starting index
354 | }
355 | }
356 |
357 | return mountainPeak; // Return the peak
358 | }
359 | }
--------------------------------------------------------------------------------