![]() |
VOOZH | about |
Given an array, arr[] of size N whose elements from left to right, must be read as an incoming stream of integers, the task is to sort the stream of integers and print accordingly.
Examples:
Input: arr[] = {2, 4, 1, 7, 3}
Output: 1 2 3 4 7
Explanation:
First element in the stream: 2 ? Sorted list: {2}
Second element in the stream: 4 ? Sorted list: {2, 4}
Third element in the stream: 1 ? Sorted list: {1, 2, 4}
Fourth element in the stream: 7 ? Sorted list: {1, 2, 4, 7}
Fifth element in the stream: 3 ? Sorted list: {1, 2, 3, 4, 7}Input: arr[] = {4, 1, 7, 6, 2}
Output: 1 2 4 6 7
Explanation:
First element in the stream: 4 ? Sorted list: {4}
Second element in the stream: 1 ? Sorted list: {1, 4}
Third element in the stream: 7 ? Sorted list: {1, 4, 7}
Fourth element in the stream: 6 ? Sorted list: {1, 4, 6, 7}
Fifth element in the stream: 2 ? Sorted list: {1, 2, 4, 6, 7}
Naive Approach: The simplest approach is to traverse the array and for each array element, linearly scan the array and find the right position of that element and place it in the array.
Below is the implementation of the above approach:
4 1 4 1 4 7 1 4 6 7 1 2 4 6 7
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to use a Binary Search to find the correct position of each element in the sorted list. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
4 1 4 1 4 7 1 4 6 7 1 2 4 6 7
Time Complexity: O(N*log N)
Auxiliary Space: O(N)