Sie sind auf Seite 1von 9

Sorting :

Alternative Sorting
Given an array of integers, print the array in such a way that the first element is first
maximum and second element is first minimum and so on.
Examples :
Input : arr[] = {7, 1, 2, 3, 4, 5, 6}
Output : 7 1 6 2 5 3 4

Input : arr[] = {1, 6, 9, 4, 3, 7, 8, 2}


Output : 9 1 8 2 7 3 6 4

A simple solution is to first print maximum element, then minimum, then second
maximum, and so on. Time complexity of this approach is O(n2).
An efficient solution involves following steps.
1) Sort input array using a O(n Log n) algorithm.
2) We maintain two pointers, one from beginning and one from end in sorted array.
We alternatively print elements pointed by two pointers and move them toward
each other.
// Java program to print an array in alternate
// sorted manner
import java.io.*;
import java.util.Arrays;
   
class AlternativeString
{
    // Function to print alternate sorted values
    static void alternateSort(int arr[], int n)
    {
        Arrays.sort(arr);
  
        // Printing the last element of array 
        // first and then first element and then 
        // second last element and then second 
        // element and so on.
        int i = 0, j = n-1;
        while (i < j) {
            System.out.print(arr[j--] + " ");
            System.out.print(arr[i++] + " ");
        }
       
        // If the total element in array is odd 
        // then print the last middle element.
        if (n % 2 != 0)
            System.out.print(arr[i]);
    }
  
    /* Driver program to test above functions */
    public static void main (String[] args)
    {
        int arr[] = {1, 12, 4, 6, 7, 10};
        int n = arr.length;
        alternateSort(arr, n);
    }
}
Output :
12 1 10 4 7 6
Time Complexity: O(n Log n)
Auxiliary Space : O(1)

Sort a nearly sorted (or K sorted)


array
Given an array of n elements, where each element is at most k away from its target
position, devise an algorithm that sorts in O(n log k) time. For example, let us
consider k is 2, an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8,
9 in the given array.
Examples:
Input : arr[] = {6, 5, 3, 2, 8, 10, 9}
k=3
Output : arr[] = {2, 3, 5, 6, 8, 9, 10}

Input : arr[] = {10, 9, 8, 7, 4, 70, 60, 50}


k=4
Output : arr[] = {4, 7, 8, 9, 10, 50, 60, 70}
/* Function to sort an array using insertion sort*/
static void insertionSort(int A[], int size) 

int i, key, j; 
for (i = 1; i < size; i++) 

    key = A[i]; 
    j = i-1; 
  
    /* Move elements of A[0..i-1], that are greater than key, to one 
        position ahead of their current position. 
        This loop will run at most k times */
    while (j >= 0 && A[j] > key) 
    { 
        A[j+1] = A[j]; 
        j = j-1; 
    } 
    A[j+1] = key; 


The inner loop will run at most k times. To move every element to its correct place,
at most k elements need to be moved. So overall complexity will be O(nk)
We can sort such arrays more efficiently with the help of Heap data structure.
Following is the detailed process that uses Heap.
1) Create a Min Heap of size k+1 with first k+1 elements. This will take O(k) time
(See this GFact)
2) One by one remove min element from heap, put it in result array, and add a new
element to heap from remaining elements.
Removing an element and adding a new element to min heap will take Logk time. So
overall complexity will be O(k) + O((n-k)*logK)
// A java program to sort a nearly sorted array
import java.util.Iterator;
import java.util.PriorityQueue;
  
class GFG 
{
    private static void kSort(int[] arr, int n, int k) 
    {
  
        // min heap
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
  
        // add first k + 1 items to the min heap
        for(int i = 0; i < k + 1; i++)
        {
            priorityQueue.add(arr[i]);
        }
  
        int index = 0;
        for(int i = k + 1; i < n; i++) 
        {
            arr[index++] = priorityQueue.peek();
            priorityQueue.poll();
            priorityQueue.add(arr[i]);
        }
  
        Iterator<Integer> itr = priorityQueue.iterator();
  
        while(itr.hasNext()) 
        {
            arr[index++] = priorityQueue.peek();
            priorityQueue.poll();
        }
  
    }
  
    // A utility function to print the array
    private static void printArray(int[] arr, int n) 
    {
        for(int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
        int k = 3;
        int arr[] = { 2, 6, 3, 12, 56, 8 };
        int n = arr.length;
        kSort(arr, n, k);
        System.out.println("Following is sorted array");
        printArray(arr, n);
    }
}
Output:
Following is sorted array
2 3 6 8 12 56
The Min Heap based method takes O(nLogk) time and uses O(k) auxiliary space.
We can also use a Balanced Binary Search Tree instead of Heap to store K+1
elements. The insert and delete operations on Balanced BST also take O(Logk) time.
So Balanced BST based method will also take O(nLogk) time, but the Heap bassed
method seems to be more efficient as the minimum element will always be at root.
Also, Heap doesn’t need extra space for left and right pointers.

Sort an array according to absolute


difference with given value
Given an array of n distinct elements and a number x, arrange array elements
according to the absolute difference with x, i. e., element having minimum difference
comes first and so on.
Note : If two or more elements are at equal distance arrange them in same sequence
as in the given array.
Examples :
Input : arr[] : x = 7, arr[] = {10, 5, 3, 9, 2}Output : arr[] = {5, 9, 10, 3, 2}Explanation:
7 - 10 = 3(abs)
7-5=2
7-3=4
7 - 9 = 2(abs)
7-2=5
So according to the difference with X,
elements are arranged as 5, 9, 10, 3, 2.
Input : x = 6, arr[] = {1, 2, 3, 4, 5} Output : arr[] = {5, 4, 3, 2, 1}
Input : x = 5, arr[] = {2, 6, 8, 3} Output : arr[] = {6, 3, 2, 8}

The idea is to use a self balancing binary search tree. We traverse input array and for
every element, we find its difference with x and store the difference as key and
element as value in self balancing binary search tree. Finally we traverse the tree and
print its inorder traversal which is required output.

// Java program to sort an array according absolute 


// difference with x. 
import java.io.*;
import java.util.*;
  
class GFG 
{
  
    // Function to sort an array according absolute 
    // difference with x.
    static void rearrange(int[] arr, int n, int x)
    {
            TreeMap<Integer, ArrayList<Integer>> m = new TreeMap<>();
              
            // Store values in a map with the difference 
            // with X as key
            for (int i = 0; i < n; i++)
            {
                int diff = Math.abs(x - arr[i]);
                if (m.containsKey(diff)) 
                {
                    ArrayList<Integer> al = m.get(diff);
                    al.add(arr[i]);
                    m.put(diff, al);
                }
                else 
                {
                        ArrayList<Integer> al = new ArrayList<>();
                        al.add(arr[i]);
                        m.put(diff,al);
                }
            }
  
            // Update the values of array
            int index = 0;
            for (Map.Entry entry : m.entrySet()) 
            {
                ArrayList<Integer> al = m.get(entry.getKey());
                for (int i = 0; i < al.size(); i++)
                        arr[index++] = al.get(i); 
            }
    }
  
    // Function to print the array
    static void printArray(int[] arr, int n)
    {
            for (int i = 0; i < n; i++)
                System.out.print(arr[i] + " ");
    }
  
    // Driver code
    public static void main(String args[])
    {
            int[] arr = {10, 5, 3, 9 ,2};
            int n = arr.length;
            int x = 7;
            rearrange(arr, n, x); 
            printArray(arr, n); 
    }
}
  
Output:
5 9 10 3 2
Time Complexity : O(n Log n)
Auxiliary Space : O(n)

Merge an array of size n into another


array of size m+n
There are two sorted arrays. First one is of size m+n containing only m elements.
Another one is of size n and contains n elements. Merge these two arrays into the
first array of size m+n such that the output is sorted.

Input: array with m+n elements (mPlusN[]).

NA => Value is not filled/available in


array mPlusN[]. There should be n such array blocks.
Input: array with n elements (N[]).

Output: N[] merged into mPlusN[] (Modified mPlusN[])

Algorithm:
Let first array be mPlusN[] and other array be N[]
1) Move m elements of mPlusN[] to end.
2) Start from nth element of mPlusN[] and 0th
element of N[] and merge them into mPlusN[].
Below is the implementation of the above algorithm :
class MergeArrays 
{
    /* Function to move m elements at the end of array mPlusN[] */
    void moveToEnd(int mPlusN[], int size) 
    {
        int i, j = size - 1;
        for (i = size - 1; i >= 0; i--) 
        {
            if (mPlusN[i] != -1) 
            {
                mPlusN[j] = mPlusN[i];
                j--;
            }
        }
    }
  
    /* Merges array N[] of size n into array mPlusN[]
       of size m+n*/
    void merge(int mPlusN[], int N[], int m, int n) 
    {
        int i = n;
          
        /* Current index of i/p part of mPlusN[]*/
        int j = 0;
          
        /* Current index of N[]*/
        int k = 0;
          
        /* Current index of output mPlusN[]*/
        while (k < (m + n)) 
        {
            /* Take an element from mPlusN[] if
            a) value of the picked element is smaller and we have
                not reached end of it
            b) We have reached end of N[] */
            if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n)) 
            {
                mPlusN[k] = mPlusN[i];
                k++;
                i++;
            } 
            else // Otherwise take element from N[]
            {
                mPlusN[k] = N[j];
                k++;
                j++;
            }
        }
    }
  
    /* Utility that prints out an array on a line */
    void printArray(int arr[], int size) 
    {
        int i;
        for (i = 0; i < size; i++) 
            System.out.print(arr[i] + " ");
  
        System.out.println("");
    }
  
    public static void main(String[] args) 
    {
        MergeArrays mergearray = new MergeArrays();
          
        /* Initialize arrays */
        int mPlusN[] = {2, 8, -1, -1, -1, 13, -1, 15, 20};
        int N[] = {5, 7, 9, 25};
        int n = N.length;
        int m = mPlusN.length - n;
  
        /*Move the m elements at the end of mPlusN*/
        mergearray.moveToEnd(mPlusN, m + n);
  
        /*Merge N[] into mPlusN[] */
        mergearray.merge(mPlusN, N, m, n);
  
        /* Print the resultant mPlusN */
        mergearray.printArray(mPlusN, m + n);
    }
}
  
Output:
2 5 7 8 9 13 15 20 25
Time Complexity: O(m+n)

Sort an array which contain 1 to n


values
You have given an array which contain 1 to n element, your task is to sort this array
in an efficient way and without replace with 1 to n numbers.
Examples :
Input : arr[] = {10, 7, 9, 2, 8,
3, 5, 4, 6, 1};
Output : 1 2 3 4 5 6 7 8 9 10
Native approach :
Sort this array with the use of any type of sorting method. it takes O(nlogn)
minimum time.
Efficient approach :
Replace every element with it’s position. it takes O(n) efficient time and give you the
sorted array. Let’s understand this approach with the code below.
// Efficient Java program to sort an 
// array of numbers in range from 1
// to n.
import java.io.*;
import java.util.*;
  
public class GFG {
      
          
    // function for sort array
    static void sortit(int []arr, int n)
    {
        for (int i = 0; i < n; i++) 
        {
            arr[i]=i+1;
      
              
        }
    }
      
    // Driver code
    public static void main(String args[])
    {
        int []arr = {10, 7, 9, 2, 8, 
                            3, 5, 4, 6, 1};
        int n = arr.length;
      
        // for sort an array
        sortit(arr, n);
      
        // for print all the 
        // element in sorted way
        for (int i = 0; i < n; i++) 
            System.out.print(arr[i] + " "); 
    }
}
Output :
1 2 3 4 5 6 7 8 9 10

Das könnte Ihnen auch gefallen