Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
AhmedLSayed9 committed May 9, 2023
1 parent a4f1a7d commit 164a3de
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 14 deletions.
22 changes: 11 additions & 11 deletions searching_algorithms/kmp_string_search.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,30 @@ void main() {

int kmpSearch(String long,String short) {
final List<int> table = matchTable(short);
int shortIdx = 0;
int longIdx = 0;
int shortPointer = 0;
int longPointer = 0;
int count = 0;
while (longIdx < long.length - short.length + shortIdx + 1) {
if (short[shortIdx] != long[longIdx]) {
while (longPointer < long.length - short.length + shortPointer + 1) {
if (short[shortPointer] != long[longPointer]) {
// we found a mismatch :(
// if we just started searching the short, move the long pointer
// otherwise, move the short pointer to the end of the next potential prefix
// that will lead to a match
if (shortIdx == 0) {
longIdx += 1;
if (shortPointer == 0) {
longPointer += 1;
} else {
shortIdx = table[shortIdx - 1];
shortPointer = table[shortPointer - 1];
}
} else {
// we found a match! shift both pointers
shortIdx += 1;
longIdx += 1;
shortPointer += 1;
longPointer += 1;
// then check to see if we've found the substring in the large string
if (shortIdx == short.length) {
if (shortPointer == short.length) {
// we found a substring! increment the count
// then move the short pointer to the end of the next potential prefix
count++;
shortIdx = table[shortIdx - 1];
shortPointer = table[shortPointer - 1];
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions sorting_algorithms/insertion_sort.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ void main() {

List<int> insertionSort(List<int> arr) {
for (int i = 1; i < arr.length; i++) {
final currentVal = arr[i];
final currentValue = arr[i];
int j = i - 1;
for (; j >= 0 && arr[j] > currentVal; j--) {
for (; j >= 0 && arr[j] > currentValue; j--) {
arr[j + 1] = arr[j];
}
//j + 1 because at last iteration (j--) get executed before checking the condition
arr[j + 1] = currentVal;
arr[j + 1] = currentValue;
}
return arr;
}

0 comments on commit 164a3de

Please sign in to comment.