728x90
public class MergeSortString {
static void merge(String[] arr, int left, int middle, int right) {
// Find sizes of two subarrays to be merged
int n1 = middle - left + 1;
int n2 = right - middle;
/* Create temp arrays */
String[] L = new String[n1];
String[] R = new String[n2];
/*Copy data to temp arrays*/
System.arraycopy(arr, left, L, 0, n1);
System.arraycopy(arr, middle + 1, R, 0, n2);
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarray array
int k = left;
while (i < n1 && j < n2) {
if (L[i].compareTo(R[j]) <= 0) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using merge()
static void sort(String[] arr, int left, int right) {
if (left < right) {
// Find the middle point
int middle = left + (right - left) / 2;
// Sort first and second halves
sort(arr, left, middle);
sort(arr, middle + 1, right);
// Merge the sorted halves
merge(arr, left, middle, right);
}
}
/* A utility function to print array of size n */
static void printArray(String[] arr) {
for (String str : arr) {
System.out.print(str + " ");
}
System.out.println();
}
// Driver method
public static void main(String[] args) {
String[] arr = {"panda", "cookie", "newjeans", "twice", "blackpink"};
System.out.println("Given Array");
printArray(arr);
long startTime = System.nanoTime();
sort(arr, 0, arr.length - 1);
long endTime = System.nanoTime();
System.out.println("\nSorted array");
printArray(arr);
System.out.println("\nTime taken: " + (endTime - startTime) + " nanoseconds");
}
}
728x90
'호그와트' 카테고리의 다른 글
어느새 Java가 나의 모국어가 되었다 (0) | 2024.01.24 |
---|---|
컴퓨터랑 자바로 대화할 수 있는 지경에 이르렀다 (0) | 2023.12.11 |
panda's attack (0) | 2023.11.17 |
TwoArray.java (0) | 2023.11.14 |
어이 김 씨, 한국은 춥댜 ~ (0) | 2023.11.14 |