Skip to content

PreCourse-2 Completed #1682

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 54 additions & 14 deletions Exercise_1.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,61 @@
// Time Complexity : O(log n) → Because with each step, we cut down the search space by half.
// Space Complexity : O(1) → No extra space used apart from a few variables.
// Did this code successfully run on Leetcode: Yes
// Any problem you faced while coding this: No

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

/**
* Binary Search Algorithm
*
* @param arr - The sorted input array
* @param l - Left boundary of the search space
* @param r - Right boundary of the search space
* @param x - Element to search for
* @return - Index of the element if found, otherwise -1
*/
int binarySearch(int arr[], int l, int r, int x) {
// Continue searching while left index <= right index
while (l <= r) {
// ✅ To prevent integer overflow, use this formula
int mid = l + (r - l) / 2;

// ✅ Case 1: If middle element is equal to target → return mid
if (arr[mid] == x) {
return mid;
}
// ✅ Case 2: If middle element is smaller than target → search right side
else if (arr[mid] < x) {
l = mid + 1;
}
// ✅ Case 3: If middle element is greater than target → search left side
else {
r = mid - 1;
}
}

// ✅ If element is not present in the array
return -1;
}

// Driver method to test above
public static void main(String args[])
{

// ✅ Driver method to test the code
public static void main(String args[]) {
BinarySearch ob = new BinarySearch();

// ✅ Sample Input and Explanation:
// Sorted array (binary search only works on sorted arrays)
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
int x = 10; // Element to search for

// ✅ Call binary search
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);

// ✅ Output the result
if (result == -1) {
System.out.println("Element not present in the array.");
} else {
System.out.println("Element found at index " + result);
}
}
}
}
28 changes: 27 additions & 1 deletion Exercise_2.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
// Time Complexity :O(NlogN) → Because we are dividing the array into two halves at each step.
// Space Complexity :O(NlogN)
// Did this code successfully run on Leetcode :
// Any problem you faced while coding this :No


// Your code here along with comments explaining your approach

class QuickSort
{
/* This function takes last element as pivot,
Expand All @@ -8,11 +16,24 @@ class QuickSort
of pivot */
void swap(int arr[],int i,int j){
//Your code here
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

int partition(int arr[], int low, int high)
{
//Write code here for Partition and Swap
//Write code here for Partition and Swap
int pivot = arr[high];
int swapIndex = low;
for(int i=low; i<high; i++){
if (arr[i]<=pivot){
swap(arr, i, swapIndex);
swapIndex++;
}
}
swap(arr,swapIndex,high);
return swapIndex;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
Expand All @@ -22,6 +43,11 @@ void sort(int arr[], int low, int high)
{
// Recursively sort elements before
// partition and after partition
if(low<high){
int partitionIndex = partition(arr, low, high);
sort(arr, low, partitionIndex-1);
sort(arr, partitionIndex+1, high);
}
}

/* A utility function to print array of size n */
Expand Down
15 changes: 15 additions & 0 deletions Exercise_3.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
// Time Complexity : O(n) → Because we need to traverse the list once to find the middle.
// Space Complexity : O(1) → No extra space used apart from a few pointers.
// Did this code successfully run on Leetcode: Yes
// Any problem you faced while coding this: Nope

class LinkedList
{
Node head; // head of linked list
Expand All @@ -20,6 +25,16 @@ void printMiddle()
{
//Write your code here
//Implement using Fast and slow pointers
Node fast = head;
Node slow = head;
while(fast!=null && fast.next != null){
slow=slow.next;
fast=fast.next.next;
}
if (slow!=null){
System.out.println("Middle element is :"+slow.data);
}

}

public void push(int new_data)
Expand Down
46 changes: 46 additions & 0 deletions Exercise_4.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
// Time Complexity : O(n * log n) → because we split the array into halves and merge them back.
// Space Complexity: O(n) → because of the temporary arrays used for merging.
// Did this code successfully run on Leetcode :
// Any problem you faced while coding this : No



class MergeSort
{
// Merges two subarrays of arr[].
Expand All @@ -6,6 +13,39 @@ class MergeSort
void merge(int arr[], int l, int m, int r)
{
//Your code here
int length1 = m-l+1;
int length2 = r-m;
int[] left = new int[length1];
int [] right = new int[length2];
for(int i = 0; i < length1; i++){
left[i]= arr[l+i];
}
for(int j = 0; j < length2; j++){
right[j] = arr[m+1+j];
}
int i=0;
int j =0;
int k =l;
while(i<length1 && j<length2){
if(left[i]<=right[j]){
arr[k] = left[i];
i++;
}else{
arr[k] = right[j];
j++;
}
k++;
}
while(i<length1){
arr[k] = left[i];
i++;
k++;
}
while(j<length2){
arr[k] = right[j];
j++;
k++;
}
}

// Main function that sorts arr[l..r] using
Expand All @@ -14,6 +54,12 @@ void sort(int arr[], int l, int r)
{
//Write your code here
//Call mergeSort from here
if(l<r){
int mid = l + (r-l)/2;
sort(arr, l, mid);
sort(arr, mid+1, r);
merge(arr, l, mid, r);
}
}

/* A utility function to print array of size n */
Expand Down
77 changes: 58 additions & 19 deletions Exercise_5.java
Original file line number Diff line number Diff line change
@@ -1,36 +1,75 @@
// Time Complexity : O(n * log n) in average case, O(n^2) in worst case
// Space Complexity : O(log n) due to the stack used for iterative calls
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No


class IterativeQuickSort {
void swap(int arr[], int i, int j)
{
//Try swapping without extra variable
void swap(int arr[], int i, int j) {
// Swapping without extra variable
arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];
}

/* This function is same in both iterative and
recursive*/
int partition(int arr[], int l, int h)
{
//Compare elements and swap.
/* This function is same in both iterative and recursive */
int partition(int arr[], int l, int h) {
int pivot = arr[h];
int i = (l - 1);
for (int j = l; j <= h - 1; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, h);
return (i + 1);
}

// Sorts arr[l..h] using iterative QuickSort
void QuickSort(int arr[], int l, int h)
{
//Try using Stack Data Structure to remove recursion.
void QuickSort(int arr[], int l, int h) {
// Create an auxiliary stack
int[] stack = new int[h - l + 1];
int top = -1;

// Push initial values to stack
stack[++top] = l;
stack[++top] = h;

while (top >= 0) {
// Pop h and l
h = stack[top--];
l = stack[top--];

// Partition the array and get the pivot
int p = partition(arr, l, h);

// If there are elements on the left side of pivot, push them to stack
if (p - 1 > l) {
stack[++top] = l;
stack[++top] = p - 1;
}

// If there are elements on the right side of pivot, push them to stack
if (p + 1 < h) {
stack[++top] = p + 1;
stack[++top] = h;
}
}
}

// A utility function to print contents of arr
void printArr(int arr[], int n)
{
int i;
for (i = 0; i < n; ++i)
// A utility function to print contents of array
void printArr(int arr[], int n) {
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

// Driver code to test above
public static void main(String args[])
{
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);
}
}
}