Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class Main {
- static int n, k;
- static int[] arr, aux;
- // from arr[lo] to arr[mid] is sorted
- // from arr[mid+1] to arr[hi] is sorted
- // at the end of the procedure: from arr[lo] to arr[hi] is sorted
- static void merge(int lo, int mid, int hi) { // O(n) where n = hi-lo+1
- for (int k = lo; k <= hi; k++) {
- aux[k] = arr[k];
- }
- int i = lo, j = mid + 1;
- for (int k = lo; k <= hi; k++) {
- if (i > mid)
- arr[k] = aux[j++];
- else if (j > hi)
- arr[k] = aux[i++];
- else if (aux[j] < aux[i])
- arr[k] = aux[j++];
- else
- arr[k] = aux[i++];
- }
- }
- public static void main(String args[]) {
- Scanner read = new Scanner(System.in);
- n = read.nextInt(); // total number of elements
- k = read.nextInt(); // number of lists
- arr = new int[n];
- aux = new int[n];
- for (int i = 0; i < n; i++) {
- arr[i] = read.nextInt();
- }
- // Step 1: Merge arrays (1 and 2), arrays (3 and 4), and so on.
- // Step 2: Merge array (1,2 and 3,4), arrays (5,6 and 7,8), and so on
- // Step 3: Repeat...
- // sz is number of elements per list = n/k
- // important note: each step, sz will be doubled, sz = sz*2
- // assume n = 8, k = 4
- // 0 1 2 3 4 5 6 7
- // arr[] = {3, 4, 1, 2, 7, 8, 5, 6}
- // <(1)> <(2)> <(3)> <(4)>
- // Step 1: Merge arrays (1 and 2)
- // merge(lo = 0, hi = 3, mid = 1)
- // Merge arrays (3 and 4)
- // merge(lo = 4, hi = 7, mid = 5)
- // Step 2: Merge array (1,2 and 3,4)
- // merge(lo = 0, hi = 7, mid = 3)
- // we can think of the parameters as the following with the help of sz important note
- // Step 1 (sz= n/k = 8/4 = 2):
- // Merge arrays (1 and 2)
- // merge(lo = 0, hi = lo + (2*sz) - 1 = 3, mid = lo+sz-1 = 1)
- // Merge arrays (3 and 4)
- // merge(lo = 4, hi = lo + (2*sz) - 1 = 7, mid = lo+sz-1 = 5)
- // Step 2 (sz = sz*2 = 4): : Merge array (1,2 and 3,4)
- // merge(lo = 0, hi = lo + (2*sz) - 1 = 7, mid = lo+sz-1 = 3)
- // the remaining is: lo = ?
- for (int sz = n / k; sz < n; sz = sz * 2) {
- for (int lo = 0; lo < n - sz; lo += sz * 2) {
- int hi = lo + (2 * sz) - 1;
- int mid = lo + sz - 1;
- merge(lo, mid, hi);
- }
- }
- for (int i = 0; i < n; i++) {
- System.out.print(arr[i] + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement