VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-a-stream-of-integers/

⇱ Sort a stream of integers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort a stream of integers

Last Updated : 23 Jul, 2025

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:


Output: 
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:

  • Initialize an array ans[] to store the final sorted stream of numbers.
  • Traverse the array arr[] as a stream of numbers using a variable i and perform the following steps:
    • If array ans is empty, push arr[i] to ans.
    • Otherwise, find the correct position of arr[i] in the already sorted array ans[] using lower_bound() and push arr[i] at its correct position.
  • After completing the above steps, print the array ans[].

Below is the implementation of the above approach:


Output: 
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)

Comment
Article Tags: