|
| 1 | +/* |
| 2 | +question - |
| 3 | +Take 10 numbers as input from the user and sort it |
| 4 | +*/ |
| 5 | + |
| 6 | +import java.util.*; |
| 7 | +class Main |
| 8 | +{ |
| 9 | + void merge(int a[], int l, int m, int r) // merging the splited sorted arrays |
| 10 | + { |
| 11 | + //merging two arrays i.e L and R |
| 12 | + int n1 = m - l + 1; // size of the first array |
| 13 | + int n2 = r - m; // size of the second array |
| 14 | + |
| 15 | + int L[] = new int[n1]; // first array |
| 16 | + int R[] = new int[n2]; // second array |
| 17 | + |
| 18 | + for (int i = 0; i < n1; ++i) |
| 19 | + L[i] = a[l + i]; // assigning values to the first array |
| 20 | + for (int j = 0; j < n2; ++j) |
| 21 | + R[j] = a[m + 1 + j]; // assigning values to the second array |
| 22 | + |
| 23 | + int i = 0, j = 0; // pointers t array L and R respectively |
| 24 | + int k = l; // pointer to the main array |
| 25 | + while (i < n1 && j < n2) { // merging until i and j not reach end of the array |
| 26 | + if (L[i] <= R[j]) { |
| 27 | + a[k++] = L[i++]; |
| 28 | + } |
| 29 | + else { |
| 30 | + a[k++] = R[j++]; |
| 31 | + } |
| 32 | + } |
| 33 | + while (i < n1) { // merging 1st array when 2nd array is completely merged |
| 34 | + a[k++] = L[i++]; |
| 35 | + } |
| 36 | + while (j < n2) { // merging 2nd array when 1st array is completely merged |
| 37 | + a[k++] = R[j++]; |
| 38 | + } |
| 39 | + } |
| 40 | + void sort(int arr[], int l, int r) // dividing the array then merging sorted arrays |
| 41 | + { |
| 42 | + if (l < r) { |
| 43 | + int m =l+ (r-l)/2; // calculating the mid of the array |
| 44 | + sort(arr, l, m); // sorting the left part |
| 45 | + sort(arr, m + 1, r); // sorting the right part |
| 46 | + merge(arr, l, m, r); // merging the left and right part |
| 47 | + } |
| 48 | + } |
| 49 | + public static void main(String args[]) |
| 50 | + { |
| 51 | + Scanner sc= new Scanner(System.in); |
| 52 | + int arr[] = new int[10]; |
| 53 | + System.out.print("Enter ten numbers for the array"); |
| 54 | + for(int i=0; i<10; i++) |
| 55 | + { |
| 56 | + arr[i]=sc.nextInt(); // taking input |
| 57 | + } |
| 58 | + Main ob = new Main(); |
| 59 | + ob.sort(arr, 0, arr.length - 1); // sorting |
| 60 | + |
| 61 | + System.out.println("\nSorted array"); |
| 62 | + int n = arr.length; |
| 63 | + for (int i = 0; i < n; ++i) |
| 64 | + System.out.print(arr[i] + " "); // printing the sorted array |
| 65 | + System.out.println(); |
| 66 | + } |
| 67 | +} |
0 commit comments