Skip to content

Commit

Permalink
Merge pull request #20 from dvir019/main
Browse files Browse the repository at this point in the history
Add sorting algorithms in Java
  • Loading branch information
awaissaddiqui authored Oct 16, 2024
2 parents 7eb7473 + c1bd4ab commit 7fd90b6
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Sorting/Java/CountingSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import java.util.Arrays;

public class CountingSort {
public static void bucketSort(int[] arr, int low, int high) {
int[] hist = new int[high - low + 1];

for (int num : arr) {
hist[num - low]++;
}

int index = 0;

for (int i = 0; i < hist.length; i++) {
for (int j = 0; j < hist[i]; j++) {
arr[index++] = i + low;
}
}
}

public static void main(String[] args) {
int[] arr = {1, 1, 5, 2, 2, 3, 0, 0, -1, 2};

System.out.println("Unsorted array: " + Arrays.toString(arr));

bucketSort(arr, -1, 5);

System.out.println("Sorted array: " + Arrays.toString(arr));
}
}
67 changes: 67 additions & 0 deletions Sorting/Java/MergeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.util.Arrays;

class MergeSort {
private static void merge(int[] arr, int left, int middle, int right) {
int n1 = middle - left + 1;
int n2 = right - middle;

int[] leftArray = new int[n1];
int[] rightArray = new int[n2];

System.arraycopy(arr, left, leftArray, 0, n1);
for (int j = 0; j < n2; j++) {
rightArray[j] = arr[middle + 1 + j];
}

int i = 0, j = 0;

int k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}

while (i < n1) {
arr[k] = leftArray[i];
i++;
k++;
}

while (j < n2) {
arr[k] = rightArray[j];
j++;
k++;
}
}

private static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int middle = (left + right) / 2;

mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);

merge(arr, left, middle, right);
}
}

private static void mergeSort(int[] arr) {
mergeSort(arr, 0, arr.length - 1);
}

public static void main(String[] args) {
int[] arr = { 1, 5, 0, -8, 2, 1, 0, -2};

System.out.println("Unsorted array: " + Arrays.toString(arr));

mergeSort(arr);

System.out.println("Sorted array: " + Arrays.toString(arr));
}
}

0 comments on commit 7fd90b6

Please sign in to comment.