Java Program for Merge Sort in Ascending Order
public class MergeSortAscending {
public static void main(String[] args) {
// Sample array of numbers to be sorted
int[] numbers = {38, 27, 43, 3, 9, 82, 10};
// Sort the array using Merge Sort
mergeSort(numbers, 0, numbers.length);
// Display the sorted array
System.out.println("Sorted array in ascending order:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
/**
* Recursively sorts the array using the merge sort algorithm.
*
* @param arr The array to be sorted.
* @param start The starting index of the portion to be sorted.
* @param end The ending index of the portion to be sorted.
*/
public static void mergeSort(int[] arr, int start, int end) {
if (end - start < 2) {
return;
}
// Calculate the middle index
int mid = (start + end) / 2;
// Divide and recursively sort both halves
mergeSort(arr, start, mid);
mergeSort(arr, mid, end);
// Merge the two sorted halves
merge(arr, start, mid, end);
}
/**
* Merges two sorted sections of the array.
*
* @param arr The array with segments to merge.
* @param start The starting index of the first segment.
* @param mid The ending index of the first segment and starting index of the second.
* @param end The ending index of the second segment.
*/
public static void merge(int[] arr, int start, int mid, int end) {
if (arr[mid - 1] <= arr[mid]) {
return;
}
int i = start;
int j = mid;
int tempIndex = 0;
int[] temp = new int[end - start];
// Actual merging process
while (i < mid && j < end) {
temp[tempIndex++] = (arr[i] <= arr[j]) ? arr[i++] : arr[j++];
}
System.arraycopy(arr, i, arr, start + tempIndex, mid - i);
System.arraycopy(temp, 0, arr, start, tempIndex);
}
}
Output:
Sorted array in ascending order:
3 9 10 27 38 43 82
Step-by-Step Explanation:
Related Java Programs on Sorting Algorithms
- Bubble Sort in Ascending Order in Java
- Bubble Sort in Descending Order in Java
- Selection Sort in Ascending Order in Java
- Selection Sort in Descending Order in Java
- Insertion Sort in Ascending Order in Java
- Insertion Sort in Descending Order in Java
- Merge Sort in Ascending Order in Java
- Merge Sort in Descending Order in Java
- Quick Sort in Ascending Order in Java
- Quick Sort in Descending Order in Java
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment