From b239409612ce7db0a81c43183af2747941134b41 Mon Sep 17 00:00:00 2001 From: Paridhi Malviya Date: Wed, 31 Dec 2025 00:51:16 -0600 Subject: [PATCH 1/2] Complete Precourse-2. Binary Search. Quick sort. Find Mid Point of a Singly Linked List. Merge Sort. --- .DS_Store | Bin 0 -> 6148 bytes Exercise_1.cpp | 21 ---- Exercise_1.java | 21 ---- Exercise_1.js | 16 --- Exercise_1.py | 22 ---- Exercise_2.cpp | 47 --------- Exercise_2.java | 48 --------- Exercise_2.js | 41 -------- Exercise_2.py | 23 ----- Exercise_3.cpp | 50 ---------- Exercise_3.java | 53 ---------- Exercise_3.js | 43 -------- Exercise_3.py | 26 ----- Exercise_4.cpp | 43 -------- Exercise_4.java | 42 -------- Exercise_4.js | 34 ------- Exercise_4.py | 18 ---- Exercise_5.cpp | 42 -------- Exercise_5.java | 36 ------- Exercise_5.js | 36 ------- Exercise_5.py | 10 -- Precourse2-Swift/BinarySearch.swift | 62 ++++++++++++ Precourse2-Swift/IterativeQuickSort.swift | 25 +++++ Precourse2-Swift/MergeSort.swift | 92 +++++++++++++++++ .../MidPointOfASinglyLinkedList.swift | 32 ++++++ Precourse2-Swift/QuickSort.swift | 94 ++++++++++++++++++ Sample.java | 7 -- 27 files changed, 305 insertions(+), 679 deletions(-) create mode 100644 .DS_Store delete mode 100644 Exercise_1.cpp delete mode 100644 Exercise_1.java delete mode 100644 Exercise_1.js delete mode 100644 Exercise_1.py delete mode 100644 Exercise_2.cpp delete mode 100644 Exercise_2.java delete mode 100644 Exercise_2.js delete mode 100644 Exercise_2.py delete mode 100644 Exercise_3.cpp delete mode 100644 Exercise_3.java delete mode 100644 Exercise_3.js delete mode 100644 Exercise_3.py delete mode 100644 Exercise_4.cpp delete mode 100644 Exercise_4.java delete mode 100644 Exercise_4.js delete mode 100644 Exercise_4.py delete mode 100644 Exercise_5.cpp delete mode 100644 Exercise_5.java delete mode 100644 Exercise_5.js delete mode 100644 Exercise_5.py create mode 100644 Precourse2-Swift/BinarySearch.swift create mode 100644 Precourse2-Swift/IterativeQuickSort.swift create mode 100644 Precourse2-Swift/MergeSort.swift create mode 100644 Precourse2-Swift/MidPointOfASinglyLinkedList.swift create mode 100644 Precourse2-Swift/QuickSort.swift delete mode 100644 Sample.java diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 GIT binary patch literal 6148 zcmeH~Jr2S!425mzP>H1@V-^m;4Wg<&0T*E43hX&L&p$$qDprKhvt+--jT7}7np#A3 zem<@ulZcFPQ@L2!n>{z**++&mCkOWA81W14cNZlEfg7;MkzE(HCqgga^y>{tEnwC%0;vJ&^%eQ zLs35+`xjp>T0 - -// A recursive binary search function. It returns -// location of x in given array arr[l..r] is present, -// otherwise -1 -int binarySearch(int arr[], int l, int r, int x) -{ - //Your Code here -} - -int main(void) -{ - int arr[] = { 2, 3, 4, 10, 40 }; - int n = sizeof(arr) / sizeof(arr[0]); - int x = 10; - int result = binarySearch(arr, 0, n - 1, x); - (result == -1) ? printf("Element is not present in array") - : printf("Element is present at index %d", - result); - return 0; -} \ No newline at end of file diff --git a/Exercise_1.java b/Exercise_1.java deleted file mode 100644 index c3ff1141..00000000 --- a/Exercise_1.java +++ /dev/null @@ -1,21 +0,0 @@ -class BinarySearch { - // Returns index of x if it is present in arr[l.. r], else return -1 - int binarySearch(int arr[], int l, int r, int x) - { - //Write your code here - } - - // Driver method to test above - public static void main(String args[]) - { - BinarySearch ob = new BinarySearch(); - int arr[] = { 2, 3, 4, 10, 40 }; - int n = arr.length; - int x = 10; - int result = ob.binarySearch(arr, 0, n - 1, x); - if (result == -1) - System.out.println("Element not present"); - else - System.out.println("Element found at index " + result); - } -} diff --git a/Exercise_1.js b/Exercise_1.js deleted file mode 100644 index 89d853ec..00000000 --- a/Exercise_1.js +++ /dev/null @@ -1,16 +0,0 @@ -class BinarySearch { - // Returns index of x if it is present in arr[l.. r], else return -1 - function binarySearch(arr, l, r, x) { -​ - } -} -// Driver method to test above -const ob = new BinarySearch(); -const arr = [2, 3, 4, 10, 40]; -const n = arr.length; -const x = 10; -const result = ob.binarySearch(arr, 0, n - 1, x); -if (result === -1) - console.log("Element not present"); -else - console.log("Element found at index " + result); diff --git a/Exercise_1.py b/Exercise_1.py deleted file mode 100644 index 3e6adcf4..00000000 --- a/Exercise_1.py +++ /dev/null @@ -1,22 +0,0 @@ -# Python code to implement iterative Binary -# Search. - -# It returns location of x in given array arr -# if present, else returns -1 -def binarySearch(arr, l, r, x): - - #write your code here - - - -# Test array -arr = [ 2, 3, 4, 10, 40 ] -x = 10 - -# Function call -result = binarySearch(arr, 0, len(arr)-1, x) - -if result != -1: - print "Element is present at index % d" % result -else: - print "Element is not present in array" diff --git a/Exercise_2.cpp b/Exercise_2.cpp deleted file mode 100644 index c90e577e..00000000 --- a/Exercise_2.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include -using namespace std; - -// A utility function to swap two elements -void swap(int* a, int* b) -{ - //Your Code here -} - -/* This function takes last element as pivot, places -the pivot element at its correct position in sorted -array, and places all smaller (smaller than pivot) -to left of pivot and all greater elements to right -of pivot */ -int partition (int arr[], int low, int high) -{ - //Your Code here -} - -/* The main function that implements QuickSort -arr[] --> Array to be sorted, -low --> Starting index, -high --> Ending index */ -void quickSort(int arr[], int low, int high) -{ - //Your Code here -} - -/* Function to print an array */ -void printArray(int arr[], int size) -{ - int i; - for (i = 0; i < size; i++) - cout << arr[i] << " "; - cout << endl; -} - -// Driver Code -int main() -{ - int arr[] = {10, 7, 8, 9, 1, 5}; - int n = sizeof(arr) / sizeof(arr[0]); - quickSort(arr, 0, n - 1); - cout << "Sorted array: \n"; - printArray(arr, n); - return 0; -} \ No newline at end of file diff --git a/Exercise_2.java b/Exercise_2.java deleted file mode 100644 index d0b5fa5f..00000000 --- a/Exercise_2.java +++ /dev/null @@ -1,48 +0,0 @@ -class QuickSort -{ - /* This function takes last element as pivot, - places the pivot element at its correct - position in sorted array, and places all - smaller (smaller than pivot) to left of - pivot and all greater elements to right - of pivot */ - void swap(int arr[],int i,int j){ - //Your code here - } - - int partition(int arr[], int low, int high) - { - //Write code here for Partition and Swap - } - /* The main function that implements QuickSort() - arr[] --> Array to be sorted, - low --> Starting index, - high --> Ending index */ - void sort(int arr[], int low, int high) - { - // Recursively sort elements before - // partition and after partition - } - - /* A utility function to print array of size n */ - static void printArray(int arr[]) - { - int n = arr.length; - for (int i=0; i Array to be sorted, - low --> Starting index, - high --> Ending index */ - function sort(arr, low, high) { - // Recursively sort elements before - // partition and after partition - } -​ - /* A utility function to print array of size n */ - function printArray(arr) { - let n = arr.length; - for (let i = 0; i < n; ++i) - console.log(arr[i] + " "); - console.log(); - } -} - // Driver program - let arr = [10, 7, 8, 9, 1, 5]; - let n = arr.length; - let ob = new QuickSort(); - ob.sort(arr, 0, n - 1); - console.log("sorted array"); - ob.printArray(arr); diff --git a/Exercise_2.py b/Exercise_2.py deleted file mode 100644 index 35abf0dd..00000000 --- a/Exercise_2.py +++ /dev/null @@ -1,23 +0,0 @@ -# Python program for implementation of Quicksort Sort - -# give you explanation for the approach -def partition(arr,low,high): - - - #write your code here - - -# Function to do Quick sort -def quickSort(arr,low,high): - - #write your code here - -# Driver code to test above -arr = [10, 7, 8, 9, 1, 5] -n = len(arr) -quickSort(arr,0,n-1) -print ("Sorted array is:") -for i in range(n): - print ("%d" %arr[i]), - - diff --git a/Exercise_3.cpp b/Exercise_3.cpp deleted file mode 100644 index 209ce0fe..00000000 --- a/Exercise_3.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include -using namespace std; - -// Struct -struct Node -{ - int data; - struct Node* next; -}; - -/* Function to get the middle of the linked list*/ -void printMiddle(struct Node *head) -{ - //YourCode here - //Use fast and slow pointer technique -} - -// Function to add a new node -void push(struct Node** head_ref, int new_data) -{ - struct Node* new_node = new Node; - new_node->data = new_data; - new_node->next = (*head_ref); - (*head_ref) = new_node; -} - -// A utility function to print a given linked list -void printList(struct Node *ptr) -{ - while (ptr != NULL) - { - printf("%d->", ptr->data); - ptr = ptr->next; - } - printf("NULL\n"); -} - -// Driver Code -int main() -{ - struct Node* head = NULL; - for (int i=15; i>0; i--) - { - push(&head, i); - printList(head); - printMiddle(head); - } - - return 0; -} \ No newline at end of file diff --git a/Exercise_3.java b/Exercise_3.java deleted file mode 100644 index 1f9b752a..00000000 --- a/Exercise_3.java +++ /dev/null @@ -1,53 +0,0 @@ -class LinkedList -{ - Node head; // head of linked list - - /* Linked list node */ - class Node - { - int data; - Node next; - Node(int d) - { - data = d; - next = null; - } - } - - /* Function to print middle of linked list */ - //Complete this function - void printMiddle() - { - //Write your code here - //Implement using Fast and slow pointers - } - - public void push(int new_data) - { - Node new_node = new Node(new_data); - new_node.next = head; - head = new_node; - } - - public void printList() - { - Node tnode = head; - while (tnode != null) - { - System.out.print(tnode.data+"->"); - tnode = tnode.next; - } - System.out.println("NULL"); - } - - public static void main(String [] args) - { - LinkedList llist = new LinkedList(); - for (int i=15; i>0; --i) - { - llist.push(i); - llist.printList(); - llist.printMiddle(); - } - } -} \ No newline at end of file diff --git a/Exercise_3.js b/Exercise_3.js deleted file mode 100644 index 4c1eabdd..00000000 --- a/Exercise_3.js +++ /dev/null @@ -1,43 +0,0 @@ -class LinkedList { - constructor() { - this.head = null; // head of linked list - } -​ - /* Linked list node */ - static Node = class { - constructor(d) { - //Constructor here - this.data = d; - this.next = null; - } - } -​ - /* Function to print middle of linked list */ - //Complete this function - function printMiddle() { - //Write your code here - //Implement using Fast and slow pointers - } -​ - function push(new_data) { - let new_node = new this.Node(new_data); - new_node.next = this.head; - this.head = new_node; - } -​ - function printList() { - let tnode = this.head; - while (tnode != null) { - console.log(tnode.data + "->"); - tnode = tnode.next; - } - console.log("NULL"); - } -} -​ -let llist = new LinkedList(); -for (let i = 15; i > 0; --i) { - llist.push(i); - llist.printList(); - llist.printMiddle(); -} diff --git a/Exercise_3.py b/Exercise_3.py deleted file mode 100644 index a26a69b8..00000000 --- a/Exercise_3.py +++ /dev/null @@ -1,26 +0,0 @@ -# Node class -class Node: - - # Function to initialise the node object - def __init__(self, data): - -class LinkedList: - - def __init__(self): - - - def push(self, new_data): - - - # Function to get the middle of - # the linked list - def printMiddle(self): - -# Driver code -list1 = LinkedList() -list1.push(5) -list1.push(4) -list1.push(2) -list1.push(3) -list1.push(1) -list1.printMiddle() diff --git a/Exercise_4.cpp b/Exercise_4.cpp deleted file mode 100644 index 1a528ee6..00000000 --- a/Exercise_4.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include - -// Merges two subarrays of arr[]. -// First subarray is arr[l..m] -// Second subarray is arr[m+1..r] -void merge(int arr[], int l, int m, int r) -{ - //Your code here -} - -/* l is for left index and r is right index of the - sub-array of arr to be sorted */ -void mergeSort(int arr[], int l, int r) -{ - //Your code here -} - -/* UTILITY FUNCTIONS */ -/* Function to print an array */ -void printArray(int A[], int size) -{ - int i; - for (i=0; i < size; i++) - printf("%d ", A[i]); - printf("\n"); -} - -/* Driver program to test above functions */ -int main() -{ - int arr[] = {12, 11, 13, 5, 6, 7}; - int arr_size = sizeof(arr)/sizeof(arr[0]); - - printf("Given array is \n"); - printArray(arr, arr_size); - - mergeSort(arr, 0, arr_size - 1); - - printf("\nSorted array is \n"); - printArray(arr, arr_size); - return 0; -} \ No newline at end of file diff --git a/Exercise_4.java b/Exercise_4.java deleted file mode 100644 index 81afd3c2..00000000 --- a/Exercise_4.java +++ /dev/null @@ -1,42 +0,0 @@ -class MergeSort -{ - // Merges two subarrays of arr[]. - // First subarray is arr[l..m] - // Second subarray is arr[m+1..r] - void merge(int arr[], int l, int m, int r) - { - //Your code here - } - - // Main function that sorts arr[l..r] using - // merge() - void sort(int arr[], int l, int r) - { - //Write your code here - //Call mergeSort from here - } - - /* A utility function to print array of size n */ - static void printArray(int arr[]) - { - int n = arr.length; - for (int i=0; i -using namespace std; - -// A utility function to swap two elements -void swap(int* a, int* b) -{ - int t = *a; - *a = *b; - *b = t; -} - -/* This function is same in both iterative and recursive*/ -int partition(int arr[], int l, int h) -{ - //Do the comparison and swapping here -} - -/* A[] --> Array to be sorted, -l --> Starting index, -h --> Ending index */ -void quickSortIterative(int arr[], int l, int h) -{ - //Try to think that how you can use stack here to remove recursion. -} - -// A utility function to print contents of arr -void printArr(int arr[], int n) -{ - int i; - for (i = 0; i < n; ++i) - cout << arr[i] << " "; -} - -// Driver code -int main() -{ - int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; - int n = sizeof(arr) / sizeof(*arr); - quickSortIterative(arr, 0, n - 1); - printArr(arr, n); - return 0; -} \ No newline at end of file diff --git a/Exercise_5.java b/Exercise_5.java deleted file mode 100644 index 30e82675..00000000 --- a/Exercise_5.java +++ /dev/null @@ -1,36 +0,0 @@ -class IterativeQuickSort { - void swap(int arr[], int i, int j) - { - //Try swapping without extra variable - } - - /* This function is same in both iterative and - recursive*/ - int partition(int arr[], int l, int h) - { - //Compare elements and swap. - } - - // Sorts arr[l..h] using iterative QuickSort - void QuickSort(int arr[], int l, int h) - { - //Try using Stack Data Structure to remove recursion. - } - - // A utility function to print contents of arr - void printArr(int arr[], int n) - { - int i; - for (i = 0; i < n; ++i) - System.out.print(arr[i] + " "); - } - - // Driver code to test above - public static void main(String args[]) - { - IterativeQuickSort ob = new IterativeQuickSort(); - int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; - ob.QuickSort(arr, 0, arr.length - 1); - ob.printArr(arr, arr.length); - } -} \ No newline at end of file diff --git a/Exercise_5.js b/Exercise_5.js deleted file mode 100644 index 01fb9e63..00000000 --- a/Exercise_5.js +++ /dev/null @@ -1,36 +0,0 @@ -class IterativeQuickSort { -​ - function swap(arr, i, j) { -​ - //Try swapping without extra variable -​ - } -​ - /* This function is same in both iterative and - recursive*/ - function partition(arr, l, h) { -​ - //Compare elements and swap. -​ - } -​ - // Sorts arr[l..h] using iterative QuickSort - function QuickSort(arr, l, h) { -​ - //Try using Stack Data Structure to remove recursion. -​ - } -​ - // A utility function to print contents of arr - function printArr(arr, n) { - let i; - for (i = 0; i < n; ++i) - console.log(arr[i] + " "); - } -} -​ - // Driver code to test above -let ob = new IterativeQuickSort(); -let arr = [4, 3, 5, 2, 1, 3, 2, 3]; -ob.QuickSort(arr, 0, arr.length - 1); -ob.printArr(arr, arr.length); diff --git a/Exercise_5.py b/Exercise_5.py deleted file mode 100644 index 1da24ffb..00000000 --- a/Exercise_5.py +++ /dev/null @@ -1,10 +0,0 @@ -# Python program for implementation of Quicksort - -# This function is same in both iterative and recursive -def partition(arr, l, h): - #write your code here - - -def quickSortIterative(arr, l, h): - #write your code here - diff --git a/Precourse2-Swift/BinarySearch.swift b/Precourse2-Swift/BinarySearch.swift new file mode 100644 index 00000000..b54fb3bc --- /dev/null +++ b/Precourse2-Swift/BinarySearch.swift @@ -0,0 +1,62 @@ +// +// Untitled.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 12/17/25. +// + +/* + prerequisites - the array must be sorted. + access to any element in the data structure should take constant time. + 2 approaches - iterative bonary search algorithm, recursive binary search algorithm + complexity to search for an element - O(log n) +*/ + +class BinarySearch { + + func binarySearch(for target: Int, in array: [Int]) -> Int? { + var left = 0 + var right = array.count - 1 + while left <= right { + let middle = (left + right) / 2 + let value = array[middle] + if value == target { + return middle //target found, return it's index + } else if value < target { + left = middle + 1 //target is in the right half + } else { + right = middle - 1 //target is in the left half + } + } + return -1 //Target not found + } + + init() { + let sortedArray = [2, 5, 8, 12, 16, 23, 38, 56, 71, 91] + let targetValue = 23 + if let index = binarySearch(for: targetValue, in: sortedArray) { + print("element \(targetValue) found at index \(index)") + } else { + print("Element \(targetValue) not found in the array") + } + } + + func recursiveBinarySearch(for target: Int, in array: [Int], left: Int = 0, right: Int?) -> Int? { + + let right = right ?? array.count - 1 + + guard left < right else { + return nil + } + + let middle = (left + right) / 2 + let value = array[middle] + if target == value { + return middle + } else if value < target { + return recursiveBinarySearch(for: target, in: array, left: middle + 1, right: right) + } else { + return recursiveBinarySearch(for: target, in: array, left: left, right: middle - 1) + } + } +} diff --git a/Precourse2-Swift/IterativeQuickSort.swift b/Precourse2-Swift/IterativeQuickSort.swift new file mode 100644 index 00000000..e769db40 --- /dev/null +++ b/Precourse2-Swift/IterativeQuickSort.swift @@ -0,0 +1,25 @@ +// +// InerativeQuickSort.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 12/22/25. +// + +class IterativeQuickSort { + + init() { + iterativeQuickSort() + } + + func iterativeQuickSort() { + + } + + //first write the function of partitioning the array based on a pivot + func partitionTheArrayBasedOnAPivot(array: [Int]) -> [Int] { + + + + return [] + } +} diff --git a/Precourse2-Swift/MergeSort.swift b/Precourse2-Swift/MergeSort.swift new file mode 100644 index 00000000..55bf45bb --- /dev/null +++ b/Precourse2-Swift/MergeSort.swift @@ -0,0 +1,92 @@ +// +// MergeSort.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 12/22/25. +// + +class MergeSort { + + init() { + let a = [1, 2, 14, 23, 5, 80, 10] +// let b = [2, 4, 6, 8, 10] + let result = sortUsingMergeSort(inputArray: a, low: 0, high: a.count - 1) + print("result is \(result) using merge sort") + } + + func sortUsingMergeSort(inputArray: [Int], low: Int, high: Int) -> [Int] { + //base case - if only 1 element is left + if (low == high) { + return [inputArray[low]] + } + + let mid = (low + high) / 2 + let firstSortedArray = sortUsingMergeSort(inputArray: inputArray, low: low, high: mid) + let secondSortedArray = sortUsingMergeSort(inputArray: inputArray, low: mid + 1, high: high) + + let sortedArray = mergeTwoSortedArray(a: firstSortedArray, b: secondSortedArray) + return sortedArray + } + + func mergeTwoSortedArray(a: [Int], b: [Int]) -> [Int] { + var resultArray = [Int]() + + var i = 0 + var j = 0 + + while (i < a.count && j < b.count) { + if (a[i] < b[j]) { + resultArray.append(a[i]) + i += 1 + } else { + resultArray.append(b[j]) + j += 1 + } + } + + while(i < a.count) { + resultArray.append(a[i]) + i += 1 + } + while(j < b.count) { + resultArray.append(b[j]) + j += 1 + } + + return resultArray + } + + func mergeTwoSortedArrays(a: [Int], b: [Int]) -> [Int] { + var resultArray = Array(repeating: 0, count: a.count + b.count) + var i = 0 + var j = 0 + var k = 0 + print("resultARray \(resultArray)") + while (i < a.count && j < b.count) { + if a[i] < b[j] { + resultArray[k] = a[i] + i += 1 + k += 1 + } else { + resultArray[k] = b[j] + j += 1 + k += 1 + } + } + + while (i < a.count) { + resultArray[k] = a[i] + i += 1 + k += 1 + } + + while (j < b.count) { + resultArray[k] = b[j] + j += 1 + k += 1 + } + return resultArray + } +} + + diff --git a/Precourse2-Swift/MidPointOfASinglyLinkedList.swift b/Precourse2-Swift/MidPointOfASinglyLinkedList.swift new file mode 100644 index 00000000..2df86583 --- /dev/null +++ b/Precourse2-Swift/MidPointOfASinglyLinkedList.swift @@ -0,0 +1,32 @@ +// +// MidPointOfASinglyLinkedList.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 12/22/25. +// + +class MidPointOfASinglyLinkedList { + + init() { + let linkedList = SinglyLinkedList() + linkedList.append(value: 1) + linkedList.append(value: 4) + linkedList.append(value: 2) + linkedList.append(value: 6) + linkedList.append(value: 10) + + findLLMidPoint(linkedList: linkedList) + } + + func findLLMidPoint(linkedList: SinglyLinkedList) { + + var slow = linkedList.currentHead() + var fast = linkedList.currentHead() + while (fast?.next != nil && fast?.next?.next != nil) { + slow = slow?.next + fast = fast?.next?.next + } + print("mid point of the linked list is \(slow?.value, default: "NA")") + } + +} diff --git a/Precourse2-Swift/QuickSort.swift b/Precourse2-Swift/QuickSort.swift new file mode 100644 index 00000000..e213c203 --- /dev/null +++ b/Precourse2-Swift/QuickSort.swift @@ -0,0 +1,94 @@ +// +// QuickSort.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 12/17/25. +// + +class QuickSort { + + init() { + var array = [8, 5, 1, 3, 7, 2, 9, 6] + quickSort(array: &array, low: 0, high: 7) + } +} + +extension QuickSort { + + //Based on a condition, if we need to partition an array in 2 subsets then this can be used. + /* + popular questions related to this: + 1. odd even numbers separation + 2. separate elements <= pivot and elements > pivot + 3. separate 0s and non 0s + 4. separate 0s and 1s + */ + + func quickSort(array: inout [Int], low: Int, high: Int) { + + if (low >= high) { + return + } + //first get the pivot point + let pivot: Int = array[high] + let pivotIndex = partition(input: &array, pivot: pivot, low: low, high: high) + quickSort(array: &array, low: low, high: pivotIndex - 1) + quickSort(array: &array, low: pivotIndex + 1, high: high) + + print("sorted array \(array)") + } + + func partition(input: inout [Int], pivot: Int, low: Int, high: Int) -> Int { + /* + 3 subgroups - + i to end - unknown, unvisited + 0 to j- 1 -> less than or equal to pivot + j - (i-1) -> greater than pivot + */ + var i = low + var j = low + while (i <= high) { + if (input[i] <= pivot) { + swap(array: &input, i: i, j: j) + i += 1 + j += 1 + } else { + i += 1 + } + } + return (j - 1) //pivot index + } + + func partitionAnArrayWithPivot() { + //Partiiotn an array with a pivot element so that the less than or equal to elements are towards the left side and greater elements are at the right side of the pivot element. + var inputArray = [7, 9, 4, 8, 3, 6, 2, 1] + let pivot = 5 + + /* + 3 regions + i to end -> unknown elements + 0 to (j - 1) -> elements <= pivot + (j) to (i - 1) -> elements > pivot + */ + var i = 0 + var j = 0 + while (i < inputArray.count) { + if (inputArray[i] > pivot) { + i += 1 + } else if (inputArray[i] <= pivot) { + swap(array: &inputArray, i: i, j: j) + i += 1 + j += 1 + } + } + print("updated array \(inputArray)") + let _ = partition(input: &inputArray, pivot: 6, low: 0, high: 7) + } + + func swap(array: inout [Int], i: Int, j: Int) { + let temp = array[i] + array[i] = array[j] + array[j] = temp + } + +} diff --git a/Sample.java b/Sample.java deleted file mode 100644 index 1739a9cb..00000000 --- a/Sample.java +++ /dev/null @@ -1,7 +0,0 @@ -// Time Complexity : -// Space Complexity : -// Did this code successfully run on Leetcode : -// Any problem you faced while coding this : - - -// Your code here along with comments explaining your approach From 39c22507008960f0a2e8418e6a4b55ea19133285 Mon Sep 17 00:00:00 2001 From: Paridhi Malviya Date: Wed, 31 Dec 2025 10:40:50 -0600 Subject: [PATCH 2/2] Complete Precourse-2 --- .DS_Store | Bin 6148 -> 6148 bytes .../BinarySearch.swift | 21 ++- Precourse2- Swift/IterativeQuickSort.swift | 68 ++++++++ .../LinkedListToStackAdapter.swift | 159 ++++++++++++++++++ .../MergeSort.swift | 1 - .../MidPointOfASinglyLinkedList.swift | 0 .../QuickSort.swift | 34 ---- Precourse2- Swift/SinglyLinkedList.swift | 73 ++++++++ Precourse2-Swift/IterativeQuickSort.swift | 25 --- 9 files changed, 310 insertions(+), 71 deletions(-) rename {Precourse2-Swift => Precourse2- Swift}/BinarySearch.swift (96%) create mode 100644 Precourse2- Swift/IterativeQuickSort.swift create mode 100644 Precourse2- Swift/LinkedListToStackAdapter.swift rename {Precourse2-Swift => Precourse2- Swift}/MergeSort.swift (98%) rename {Precourse2-Swift => Precourse2- Swift}/MidPointOfASinglyLinkedList.swift (100%) rename {Precourse2-Swift => Precourse2- Swift}/QuickSort.swift (57%) create mode 100644 Precourse2- Swift/SinglyLinkedList.swift delete mode 100644 Precourse2-Swift/IterativeQuickSort.swift diff --git a/.DS_Store b/.DS_Store index 5008ddfcf53c02e82d7eee2e57c38e5672ef89f6..787d903e73e9c517c7905a0d0979d52791c45420 100644 GIT binary patch delta 139 zcmZoMXfc=|&e%3FQEZ}~q9`K+0|O8XFfjNsxH9N5S5Rf#Cre1U}K^;J4n}NZVny}#(jkpCZe delta 67 zcmZoMXfc=|&Zs)EP;8=}A_oHyFfuR*Y&_`3KJh} Int? { var left = 0 var right = array.count - 1 @@ -31,16 +40,6 @@ class BinarySearch { return -1 //Target not found } - init() { - let sortedArray = [2, 5, 8, 12, 16, 23, 38, 56, 71, 91] - let targetValue = 23 - if let index = binarySearch(for: targetValue, in: sortedArray) { - print("element \(targetValue) found at index \(index)") - } else { - print("Element \(targetValue) not found in the array") - } - } - func recursiveBinarySearch(for target: Int, in array: [Int], left: Int = 0, right: Int?) -> Int? { let right = right ?? array.count - 1 diff --git a/Precourse2- Swift/IterativeQuickSort.swift b/Precourse2- Swift/IterativeQuickSort.swift new file mode 100644 index 00000000..6e364a43 --- /dev/null +++ b/Precourse2- Swift/IterativeQuickSort.swift @@ -0,0 +1,68 @@ +// +// InerativeQuickSort.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 12/22/25. +// + +class IterativeQuickSort { + + init() { + var array = [8, 5, 1, 13, 7, 12, 9, 6] + iterativeQuickSort(array: &array, low: 0, high: array.count - 1) + print("sorted array using iterative quick sort \(array)") + } + + func iterativeQuickSort(array: inout [Int], low: Int, high: Int) { + guard array.count > 1 else { + return + } + + //Stack stores (low, high) index pairs + let stack = StackUsingLL<(Int, Int)>(llList: LLLinkedList()) + stack.push(value: (low, high)) + + while let (low, high) = stack.pop() { + //we got low and high index + //do partition in here. We will get pivot index. then push in stack the tuple of (low, high) indices which needs to be sorted. It's the same as the recursive approach, it's just that we are creating stack of our own instead of using system's call stack + if (low >= high) { + return + } + let pivotIndex = partitionTheArrayBasedOnAPivot(array: &array, low: low, high: high, pivot: array[high]) + + //push left side + if (low < pivotIndex - 1) { + stack.push(value: (low, pivotIndex - 1)) + } + + //push right side + if (pivotIndex + 1 < high) { + stack.push(value: (pivotIndex + 1, high)) + } + } + } + + func partitionTheArrayBasedOnAPivot(array: inout [Int], low: Int, high: Int, pivot: Int) -> Int { + + /* + it makes use of 2 pointers. + 0-(j-1) pointer indicates the node which are smaller than or equal to the pivot + j - (i-1) indicates the elements larger than the pivot + i to end -> indicates the unvisited items + */ + + var j = low + var i = low + while (i <= high) { + if (array[i] <= pivot) { + if i != j { array.swapAt(i, j) } + i += 1 + j += 1 + } else { + i += 1 + } + } + //return the pivot index from here + return j - 1 + } +} diff --git a/Precourse2- Swift/LinkedListToStackAdapter.swift b/Precourse2- Swift/LinkedListToStackAdapter.swift new file mode 100644 index 00000000..ce4cfb25 --- /dev/null +++ b/Precourse2- Swift/LinkedListToStackAdapter.swift @@ -0,0 +1,159 @@ +// +// LinkedListToStackAdapter.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 12/16/25. +// + +//Implement stack using linked list + +class LLNode { + var value: T + var next: LLNode? + + init(value: T, next: LLNode?) { + self.value = value + self.next = next + } +} + +class LLLinkedList { + private var head: LLNode? + private var tail: LLNode? + + var isEmpty: Bool { + return head == nil + } + + var count: Int { + var currentHead = head + var count = 0 + while (currentHead != nil) { + count += 1 + currentHead = currentHead?.next + } + return count + } + + init() { + + } +} + +extension LLLinkedList { + func append(value: T) { + let newNode = LLNode(value: value, next: nil) + if head == nil { + //means linkedlist is empty, so set the newnode as the head and tail both + tail = newNode + head = newNode + } else { + //if linked list is not empty then do normal appending + tail?.next = newNode + tail = newNode + } + } + + func prepend(value: T) { + let newNode = LLNode(value: value, next: nil) + if head == nil { + //linked list is empty + head = LLNode(value: value, next: nil) + tail = head + } else { + // linked list is not empty + newNode.next = head + head = newNode + } + } + + func removeFirstNode() -> LLNode? { + if (head == nil) { + //it means the ll is empty + return nil + } else { + //if the ll is not empty + let currentHead = head + if let nextNode = head?.next { + head = nextNode + } else if (head?.next == nil) { + head = nil + } + return currentHead + } + } + + var currentHead: LLNode? { + return head + } +} + +extension LLLinkedList: CustomStringConvertible { + var description: String { + var currentNode = head + var descString = "[" + while currentNode != nil { + descString += "\(String(describing: currentNode?.value))" + currentNode = currentNode?.next + if (currentNode != nil) { + descString += "," + } + } + return descString + "]" + } +} + +class StackUsingLL: CustomStringConvertible { + private var llList: LLLinkedList? + + init(llList: LLLinkedList) { + self.llList = llList + } + + func push(value: T) { + //append the first element at the start of the linked list + llList?.prepend(value: value) + } + + func pop() -> T? { + //remove the first node from the linked list and return it. + let removedItem = llList?.removeFirstNode() + return removedItem?.value + } + + func peek() -> T? { + return llList?.currentHead?.value + } + + func isEmpty() -> Bool { + return llList?.isEmpty ?? true + } + + var description: String { + var currentHead = llList?.currentHead + var descString = "[" + while (currentHead != nil) { + descString += "\(currentHead!.value)" + currentHead = currentHead!.next + if (currentHead != nil) { + descString += "," + } + } + return descString + "]" + } +} + +class LinkedListToStackAdapter { + + init() { + let stack = StackUsingLL(llList: LLLinkedList()) + stack.push(value: 2) + stack.push(value: 3) + stack.push(value: 6) + let poppedElement = stack.pop() + print("popped element \(poppedElement, default: "NA")") + let topElement = stack.peek() + print("topElement \(topElement, default: "NA")") + print("printed linked list \(stack.description)") + } +} diff --git a/Precourse2-Swift/MergeSort.swift b/Precourse2- Swift/MergeSort.swift similarity index 98% rename from Precourse2-Swift/MergeSort.swift rename to Precourse2- Swift/MergeSort.swift index 55bf45bb..88ae05f8 100644 --- a/Precourse2-Swift/MergeSort.swift +++ b/Precourse2- Swift/MergeSort.swift @@ -9,7 +9,6 @@ class MergeSort { init() { let a = [1, 2, 14, 23, 5, 80, 10] -// let b = [2, 4, 6, 8, 10] let result = sortUsingMergeSort(inputArray: a, low: 0, high: a.count - 1) print("result is \(result) using merge sort") } diff --git a/Precourse2-Swift/MidPointOfASinglyLinkedList.swift b/Precourse2- Swift/MidPointOfASinglyLinkedList.swift similarity index 100% rename from Precourse2-Swift/MidPointOfASinglyLinkedList.swift rename to Precourse2- Swift/MidPointOfASinglyLinkedList.swift diff --git a/Precourse2-Swift/QuickSort.swift b/Precourse2- Swift/QuickSort.swift similarity index 57% rename from Precourse2-Swift/QuickSort.swift rename to Precourse2- Swift/QuickSort.swift index e213c203..68e096e8 100644 --- a/Precourse2-Swift/QuickSort.swift +++ b/Precourse2- Swift/QuickSort.swift @@ -16,14 +16,6 @@ class QuickSort { extension QuickSort { //Based on a condition, if we need to partition an array in 2 subsets then this can be used. - /* - popular questions related to this: - 1. odd even numbers separation - 2. separate elements <= pivot and elements > pivot - 3. separate 0s and non 0s - 4. separate 0s and 1s - */ - func quickSort(array: inout [Int], low: Int, high: Int) { if (low >= high) { @@ -58,32 +50,6 @@ extension QuickSort { } return (j - 1) //pivot index } - - func partitionAnArrayWithPivot() { - //Partiiotn an array with a pivot element so that the less than or equal to elements are towards the left side and greater elements are at the right side of the pivot element. - var inputArray = [7, 9, 4, 8, 3, 6, 2, 1] - let pivot = 5 - - /* - 3 regions - i to end -> unknown elements - 0 to (j - 1) -> elements <= pivot - (j) to (i - 1) -> elements > pivot - */ - var i = 0 - var j = 0 - while (i < inputArray.count) { - if (inputArray[i] > pivot) { - i += 1 - } else if (inputArray[i] <= pivot) { - swap(array: &inputArray, i: i, j: j) - i += 1 - j += 1 - } - } - print("updated array \(inputArray)") - let _ = partition(input: &inputArray, pivot: 6, low: 0, high: 7) - } func swap(array: inout [Int], i: Int, j: Int) { let temp = array[i] diff --git a/Precourse2- Swift/SinglyLinkedList.swift b/Precourse2- Swift/SinglyLinkedList.swift new file mode 100644 index 00000000..b06282cc --- /dev/null +++ b/Precourse2- Swift/SinglyLinkedList.swift @@ -0,0 +1,73 @@ +// +// SinglyLinkedList.swift +// DSA-Practice +// +// Created by Paridhi Malviya on 12/17/25. +// + +class SinglyLLNode { + var value: T + var next: SinglyLLNode? + + init(value: T, next: SinglyLLNode?) { + self.value = value + self.next = next + } +} + +class SinglyLinkedList { + + private var head: SinglyLLNode? + private var tail: SinglyLLNode? + + public init() { + + } + + public var isEmpty: Bool { + return head == nil + } + + //adds a new node at the fron tof the list O(1) operation + public func push(_ value: T) { + head = SinglyLLNode(value: value, next: head) + if tail == nil { + tail = head + } + } + + //Adds a new node at the end of the list with O(1) operation if tail reference is kept + func append(value: T) { + guard !isEmpty else { + push(value) + return + } + //the current tail's next pointer is set to the new node + tail?.next = SinglyLLNode(value: value, next: nil) + //the new node becomes the new tail + tail = tail?.next + } + + public func displayList() { + var currentHead = head + while currentHead != nil { + print("\(currentHead!.value) -> ") + currentHead = currentHead?.next + } + } + + public func currentHead() -> SinglyLLNode? { + return self.head + } +} + +class SinglyLinkedListImpl { + init() { + let linkedlist = SinglyLinkedList() + linkedlist.append(value: 1) + linkedlist.append(value: 2) + linkedlist.push(30) + print("Linked list contents:") + linkedlist.displayList() + } +} diff --git a/Precourse2-Swift/IterativeQuickSort.swift b/Precourse2-Swift/IterativeQuickSort.swift deleted file mode 100644 index e769db40..00000000 --- a/Precourse2-Swift/IterativeQuickSort.swift +++ /dev/null @@ -1,25 +0,0 @@ -// -// InerativeQuickSort.swift -// DSA-Practice -// -// Created by Paridhi Malviya on 12/22/25. -// - -class IterativeQuickSort { - - init() { - iterativeQuickSort() - } - - func iterativeQuickSort() { - - } - - //first write the function of partitioning the array based on a pivot - func partitionTheArrayBasedOnAPivot(array: [Int]) -> [Int] { - - - - return [] - } -}