Skip to content

Commit

Permalink
Merge pull request #2024 from aditiverma-21/main
Browse files Browse the repository at this point in the history
 Added java sorting algo code
  • Loading branch information
ajay-dhangar authored Nov 10, 2024
2 parents d1d84d7 + 3f2f0af commit 56950f3
Show file tree
Hide file tree
Showing 5 changed files with 420 additions and 0 deletions.
73 changes: 73 additions & 0 deletions java/Bubble_Sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
id: bubble-sort
sidebar_position: 3
title: Bubble Sort
sidebar_label: Bubble-Sort
description: Bubble sorting algorithm implementation in Java.
tags: [java, sorting, bubble sort]
---

## *Description*

Bubble Sort is a straightforward sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. It continues to do this until the list is sorted.

Here’s a step-by-step explanation of how Bubble Sort works:

- Start at the beginning of the list.
- Compare each pair of adjacent elements:
- If the current element is greater than the next one, swap them.
- If not, move to the next pair.
- Continue comparing and swapping until reaching the end of the list.
- After the first pass, the largest element will have "bubbled up" to the last position.
- Repeat the process, ignoring the last sorted elements in each subsequent pass, as they are already in the correct position.
- Stop when no swaps are needed on a full pass through the list.


## *Java implementation*

```
public class BubbleSort {
public static void bubbleSort(int[] array) {
int n = array.length;
boolean swapped;
// Outer loop for each pass
for (int i = 0; i < n - 1; i++) {
swapped = false;
// Inner loop for comparing adjacent elements
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap if the element is greater than the next element
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swapped = true;
}
}
// If no two elements were swapped, the array is sorted
if (!swapped) break;
}
}
// Main method for testing the Bubble Sort
public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original Array: " + java.util.Arrays.toString(array));
bubbleSort(array);
System.out.println("Sorted Array: " + java.util.Arrays.toString(array));
}
}
```

# *Complexity*

- Time Complexity: O(n^2) for average and worst case, O(n) for best case (already sorted array)
- Space Complexity: O(1)

# Best for:
- Small datasets, mostly unsorted data
80 changes: 80 additions & 0 deletions java/Insertion_Sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
id: insertion-sort
sidebar_position: 3
title: Insertion Sort
sidebar_label: Insertion-Sort
description: Insertion sorting algorithm implementation in Java.
tags: [java, sorting, insertion sort]
---

## *Description*

Insertion Sort is an intuitive, comparison-based sorting algorithm. It works by dividing the list into a "sorted" and an "unsorted" part. Each item from the unsorted part is picked and inserted into its correct position in the sorted part.

*Steps in Insertion Sort:*
- Assume the first element is already sorted.
- For each subsequent element, compare it with the elements in the sorted part:
- Shift each larger element one position to the right.
-Insert the current element into its correct position in the sorted part.
- Repeat this until the unsorted part is empty.

This approach is efficient for small or nearly sorted arrays, as the time complexity is better in these cases.


## *Java implementation*

```
public class InsertionSort {
/**
* Insertion Sort Algorithm
* Builds the sorted array one item at a time, inserting each element into its correct position.
* Time Complexity: O(n^2) in average and worst cases, O(n) in best case (for nearly sorted data)
* Space Complexity: O(1)
* Best for: Small datasets or nearly sorted data
*/
public static void insertionSort(int[] array) {
int n = array.length;
for (int i = 1; i < n; i++) {
int key = array[i];
int j = i - 1;
// Shift elements of the sorted part that are greater than `key`
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
j = j - 1;
}
// Insert `key` into its correct position
array[j + 1] = key;
}
}
// Main method for testing the Insertion Sort
public static void main(String[] args) {
int[] array = {12, 11, 13, 5, 6};
System.out.println("Original Array: " + java.util.Arrays.toString(array));
insertionSort(array);
System.out.println("Sorted Array: " + java.util.Arrays.toString(array));
}
}
```

# *Explanation of Code:*
- Outer Loop: Starts from the second element (since a single element is trivially sorted).
- Inner Loop (while loop): Moves elements one position to the right if they are greater than the key.
- Insertion: Once the correct position is found, the key is placed in the sorted part.

*Time Complexity*
- Worst and Average Case:
𝑂(𝑛^2), occurs when elements are in reverse order.
- Best Case:
𝑂(𝑛), occurs when the array is already sorted (each element only needs one comparison).

*Space Complexity*
Space Complexity: 𝑂(1)
- O(1), as it only requires a few extra variables for swaps.
- Insertion Sort is more efficient than some other
- 𝑂(𝑛^2) algorithms (like Bubble Sort) for small or nearly sorted arrays. It’s also a stable sorting algorithm, meaning it preserves the order of equal elements.
102 changes: 102 additions & 0 deletions java/Merge_Sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
id: merge-sort
sidebar_position: 3
title: Merge Sort
sidebar_label: Merge-Sort
description: Merge sorting algorithm implementation in Java.
tags: [java, sorting, merge sort]
---

## *Description*

Merge Sort is an efficient, stable, and comparison-based sorting algorithm. It uses the "divide and conquer" approach, dividing the array into halves, recursively sorting each half, and then merging the sorted halves back together.

Steps in Merge Sort:
- Divide: Split the array into two halves.
- Conquer: Recursively sort each half.
- Combine: Merge the two sorted halves into a single sorted array.

## *Java implementation*

```
public class MergeSort {
public static void mergeSort(int[] array, int left, int right) {
if (left < right) {
// Find the middle point
int mid = (left + right) / 2;
// Sort the first and second halves
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
// Merge the sorted halves
merge(array, left, mid, right);
}
}
// Helper method to merge two halves
private static void merge(int[] array, int left, int mid, int right) {
// Sizes of the two subarrays
int n1 = mid - left + 1;
int n2 = right - mid;
// Create temporary arrays
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
// Copy data to temp arrays
System.arraycopy(array, left, leftArray, 0, n1);
System.arraycopy(array, mid + 1, rightArray, 0, n2);
// Merge the temp arrays back into the original array
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k++] = leftArray[i++];
} else {
array[k++] = rightArray[j++];
}
}
// Copy remaining elements of leftArray
while (i < n1) {
array[k++] = leftArray[i++];
}
// Copy remaining elements of rightArray
while (j < n2) {
array[k++] = rightArray[j++];
}
}
// Main method for testing the Merge Sort
public static void main(String[] args) {
int[] array = {12, 11, 13, 5, 6, 7};
System.out.println("Original Array: " + java.util.Arrays.toString(array));
mergeSort(array, 0, array.length - 1);
System.out.println("Sorted Array: " + java.util.Arrays.toString(array));
}
}
```

# *Explanation of Code:*
- Recursive mergeSort Method: This method divides the array into halves recursively until each subarray contains a single element (a trivially sorted array).
- merge Method: This method merges two sorted halves by comparing elements and arranging them in order, placing the merged result back into the original array.
- Temporary Arrays: leftArray and rightArray are used to hold the elements of the two halves temporarily during the merge.

# *Time Complexity*
- All Cases (best, average, and worst):
- 𝑂(𝑛log𝑛), as it always splits the array and performs a linear merge.

# *Space Complexity*
- Space Complexity: 𝑂(𝑛), since it requires extra storage for the temporary arrays during merging.

# *Advantages of Merge Sort*
- Stable: Merge Sort preserves the order of equal elements.
- Consistent Performance: Its time complexity is 𝑂(𝑛log𝑛) for all cases, making it a reliable choice for large datasets.

However, Merge Sort uses extra memory for merging, which makes it less ideal in memory-constrained environments.
96 changes: 96 additions & 0 deletions java/Quick_Sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
---
id: quick-sort
sidebar_position: 3
title: Quick Sort
sidebar_label: Quick-Sort
description: Quick sorting algorithm implementation in Java.
tags: [java, sorting, quick sort]
---

## *Description*

QuickSort is a highly efficient sorting algorithm that uses the "divide and conquer" approach. It works by selecting a "pivot" element, partitioning the array around the pivot, and recursively sorting the partitions.

Steps in QuickSort:
- Choose a Pivot: Select a pivot element (commonly the last element, but other methods exist).
- Partition: Rearrange the array so elements smaller than the pivot are on the left, and elements larger are on the right.
- Recursively Sort: Apply the same process to the left and right subarrays.
- Combine: Since each subarray is sorted in place, no additional combination step is needed.

## *Java implementation*

```
public class QuickSort {
public static void quickSort(int[] array, int low, int high) {
if (low < high) {
// Partition the array and get the pivot index
int pivotIndex = partition(array, low, high);
// Recursively sort elements before and after the partition
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
}
// Helper method to partition the array around a pivot
private static int partition(int[] array, int low, int high) {
// Choose the last element as the pivot
int pivot = array[high];
int i = low - 1; // Index of the smaller element
for (int j = low; j < high; j++) {
// If current element is smaller than or equal to pivot
if (array[j] <= pivot) {
i++;
// Swap array[i] and array[j]
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// Place the pivot element at the correct position
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1; // Return the pivot index
}
// Main method for testing QuickSort
public static void main(String[] args) {
int[] array = {10, 7, 8, 9, 1, 5};
System.out.println("Original Array: " + java.util.Arrays.toString(array));
quickSort(array, 0, array.length - 1);
System.out.println("Sorted Array: " + java.util.Arrays.toString(array));
}
}
```

# *Explanation of Code:*
- Recursive quickSort Method: This method partitions the array, then recursively sorts the subarrays on either side of the pivot.
- partition Method: This method arranges elements around a chosen pivot. Elements less than or equal to the pivot move to the left, and greater elements move to the right. The pivot is placed at its correct sorted position.
- Swapping: In both partitioning and sorting, elements are swapped in place, reducing the need for extra memory.

# *Time Complexity*

- Average Case:
𝑂(𝑛log𝑛), when the pivot divides the array into balanced halves.

- Worst Case:
𝑂(𝑛^2), if the pivot divides the array poorly (e.g., when the array is already sorted, and the pivot is always the smallest or largest element).

To avoid the worst-case performance, Randomized QuickSort is often used, where the pivot is chosen randomly, reducing the likelihood of poor splits.

# *Space Complexity*
Space Complexity:
𝑂(log𝑛) due to the recursion stack in the average case.

# *Advantages of QuickSort*
- In-Place Sorting: Uses minimal additional memory.
- Efficient: Generally faster than other 𝑂(𝑛log𝑛) algorithms (like Merge Sort) for large datasets.

QuickSort is commonly used in many real-world applications due to its efficiency and relatively low memory usage compared to algorithms like Merge Sort.
Loading

0 comments on commit 56950f3

Please sign in to comment.