📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
Comments
Post a Comment
Leave Comment