Sort the Half Sorted Java
- Get link
- X
- Other Apps
PROGRAM TO SORT AN ARRAY WHEN TWO HALVES ARE SORTED
import java.io.*;import java.util.*;class GFG { public static void sortTwoHalfs(int a[], int n) { int i = 0; int j = n / 2; // loop until end of array while (j < n) { // if two pointer is equal then go // to next element of second half. if (i == j) j++; // if element of first half is bigger // than element of second half swap two // elements and go next element of first half. if (j < n && a[i] > a[j]) { // Swap elements int temp = a[i]; a[i] = a[j]; a[j] = temp; } i++; } } // Driver Code public static void main(String[] args) { int a[] = { 2, 3, 8, -1, 7, 10 }; int n = a.length; sortTwoHalfs(a, n); // Call func. to sort array. // Print sorted array for (int i = 0; i < n; i++) { System.out.print(a[i] + " "); } }}
OUTPUT
-1 2 3 7 8 10
- Get link
- X
- Other Apps
Comments
Post a Comment