Skip to content

Commit

Permalink
Merge and Quick sort
Browse files Browse the repository at this point in the history
  • Loading branch information
sangaryousmane committed Sep 25, 2023
1 parent 3c35d34 commit e35b390
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 5 deletions.
56 changes: 56 additions & 0 deletions src/intermediate/MergeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package intermediate;

import java.util.Arrays;

public class MergeSort {
public static void main(String[] args) {
int[] nums = {5, 4, 3, 2, 1};
System.out.println("Before: " + Arrays.toString(nums));
nums = mergeSort(nums);
System.out.println("After: " + Arrays.toString(nums));
}


static int[] mergeSort(int[] nums) {

if (nums.length == 1)
return nums;

int middle = nums.length / 2;
int[] left = mergeSort(Arrays.copyOfRange(nums, 0, middle));
int[] right = mergeSort(Arrays.copyOfRange(nums, middle, nums.length));

return merge(left, right);
}

private static int[] merge(int[] first, int[] second) {
int[] mix = new int[first.length + second.length];
int i = 0, j = 0, k = 0;

while (i < first.length && j < second.length) {
if (first[i] < second[j]) {
mix[k] = first[i];
i++;
} else {
mix[k] = second[j];
j++;
}
k++;
}

// At the end, it may be possible that one of the arrays it not complete
// copy the remaining elements. Please note that either of the loops will run
while (i < first.length) {
mix[k] = first[i];
i++;
k++;
}

while (j < second.length) {
mix[k] = second[j];
j++;
k++;
}
return mix;
}
}
10 changes: 5 additions & 5 deletions src/intermediate/Sorting.java
Original file line number Diff line number Diff line change
Expand Up @@ -192,25 +192,25 @@ private static int getMaxIndex(int[] arr, int start, int lastIndex) {
}

public static void bubbleSort(int[] arr) {
// boolean isSwapped;
boolean isSwapped;
// Get an outer for loop as a counter
// Get an inner for loop for swapping elements of the array
// if the current element is greater than the previous element, swap
System.out.println(Arrays.toString(arr));
for (int i = 0; i < arr.length; i++) {
// isSwapped = false;
isSwapped = false;

for (int j = 1; j < arr.length - i; j++) {
if (arr[j] < arr[j - 1]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
// isSwapped = true;
isSwapped = true;
System.out.println(Arrays.toString(arr));
}
}
// if (!isSwapped) // if there was no swapping
// break;
if (!isSwapped) // if there was no swapping
break;
}
}

Expand Down

0 comments on commit e35b390

Please sign in to comment.