📜  对整数流进行排序

📅  最后修改于: 2021-09-06 05:20:36             🧑  作者: Mango

给定一个大小为N的数组arr[] ,其元素从左到右必须作为传入的整数流读取,任务是对整数流进行排序并相应地打印。

例子:

朴素的方法:最简单的方法是遍历数组,对于每个数组元素,线性扫描数组并找到该元素的正确位置并将其放入数组中。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to sort a stream of integers
void Sort(vector& ans, int num)
{
    // Stores the position of
    // array elements
    int pos = -1;
 
    // Traverse through the array
    for (int i = 0; i < ans.size(); i++) {
 
        // If any element is found to be
        // greater than the current element
        if (ans[i] >= num) {
            pos = i;
            break;
        }
    }
 
    // If an element > num is not present
    if (pos == -1)
        ans.push_back(num);
 
    // Otherwise, place the number
    // at its right position
    else
        ans.insert(ans.begin() + pos, num);
}
 
// Function to print the sorted stream of integers
void sortStream(int arr[], int N)
{
    // Stores the sorted stream of integers
    vector ans;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Function Call
        Sort(ans, arr[i]);
 
        // Print the array after
        // every insertion
        for (int i = 0; i < ans.size(); i++) {
            cout << ans[i] << " ";
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 1, 7, 6, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    sortStream(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to sort a stream of integers
static void Sort(Vector ans, int num)
{
     
    // Stores the position of
    // array elements
    int pos = -1;
 
    // Traverse through the array
    for(int i = 0; i < ans.size(); i++)
    {
         
        // If any element is found to be
        // greater than the current element
        if (ans.get(i) >= num)
        {
            pos = i;
            break;
        }
    }
 
    // If an element > num is not present
    if (pos == -1)
        ans.add(num);
 
    // Otherwise, place the number
    // at its right position
    else
        ans.add(pos, num);
}
 
// Function to print the sorted stream of integers
static void sortStream(int arr[], int N)
{
     
    // Stores the sorted stream of integers
    Vector ans = new Vector();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Function Call
        Sort(ans, arr[i]);
 
        // Print the array after
        // every insertion
        for(int j = 0; j < ans.size(); j++)
        {
            System.out.print(ans.get(j) + " ");
        }
        System.out.println();
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, 1, 7, 6, 2 };
    int N = arr.length;
 
    sortStream(arr, N);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python program for the above approach
 
# Function to sort a stream of integers
def Sort(ans, num):
   
    # Stores the position of
    # array elements
    pos = -1;
 
    # Traverse through the array
    for  i in range(len(ans)):
 
        # If any element is found to be
        # greater than the current element
        if (ans[i] >= num):
            pos = i;
            break;
 
    # If an element > num is not present
    if (pos == -1):
        ans.append(num);
 
    # Otherwise, place the number
    # at its right position
    else:
        ans.insert(pos,num);
    return ans;
 
# Function to print the sorted stream of integers
def sortStream(arr, N):
   
    # Stores the sorted stream of integers
    ans = list();
 
    # Traverse the array
    for i in range(N):
 
        # Function Call
        ans = Sort(ans, arr[i]);
 
        # Print the array after
        # every insertion
        for j in range(len(ans)):
            print(ans[j], end = " ");
 
        print();
 
# Driver Code
if __name__ == '__main__':
    arr = [4, 1, 7, 6, 2];
    N = len(arr);
 
    sortStream(arr, N);
 
# This code is contributed by 29AjayKumar


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to sort a stream of integers
static void Sort(List ans, int num)
{
     
    // Stores the position of
    // array elements
    int pos = -1;
 
    // Traverse through the array
    for(int i = 0; i < ans.Count; i++)
    {
         
        // If any element is found to be
        // greater than the current element
        if (ans[i] >= num)
        {
            pos = i;
            break;
        }
    }
 
    // If an element > num is not present
    if (pos == -1)
        ans.Add(num);
 
    // Otherwise, place the number
    // at its right position
    else
        ans.Insert(pos, num);
}
 
// Function to print the sorted stream of integers
static void sortStream(int []arr, int N)
{
     
    // Stores the sorted stream of integers
    List ans = new List();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Function Call
        Sort(ans, arr[i]);
 
        // Print the array after
        // every insertion
        for(int j = 0; j < ans.Count; j++)
        {
            Console.Write(ans[j] + " ");
        }
        Console.WriteLine();
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 4, 1, 7, 6, 2 };
    int N = arr.Length;
    sortStream(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to sort a stream of integers
void Sort(vector& ans, int num)
{
    // If the element is greater than
    // all the elements in the sorted
    // array, then it push at the back
    if (lower_bound(ans.begin(),
                    ans.end(), num)
        == ans.end()) {
        ans.push_back(num);
    }
 
    // Otherwise, find its correct position
    else {
        int pos = lower_bound(ans.begin(),
                              ans.end(),
                              num)
                  - ans.begin();
 
        // Insert the element
        ans.insert(ans.begin() + pos,
                   num);
    }
}
 
// Function to print the sorted stream of integers
void sortStream(int arr[], int N)
{
    // Stores the sorted stream of integers
    vector ans;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Function Call
        Sort(ans, arr[i]);
 
        // Print the array after
        // every insertion
        for (int i = 0; i < ans.size(); i++) {
            cout << ans[i] << " ";
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 1, 7, 6, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    sortStream(arr, N);
 
    return 0;
}


输出:
4 
1 4 
1 4 7 
1 4 6 7 
1 2 4 6 7

时间复杂度: O(N 2 )
辅助空间: O(N)

高效方法:为了优化上述方法,其思想是使用二分搜索来找到每个元素在排序列表中的正确位置。请按照以下步骤解决问题:

  • 初始化数组ans[]以存储最终排序的数字流。
  • 使用变量i作为数字流遍历数组arr[]并执行以下步骤:
    • 如果数组ans为空,则将arr[i]推送到ans
    • 否则,查找ARR [I]中的已排序阵列ANS []使用LOWER_BOUND()在其正确位置的正确位置和推ARR [i]中
  • 完成上述步骤后,打印数组ans[]

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to sort a stream of integers
void Sort(vector& ans, int num)
{
    // If the element is greater than
    // all the elements in the sorted
    // array, then it push at the back
    if (lower_bound(ans.begin(),
                    ans.end(), num)
        == ans.end()) {
        ans.push_back(num);
    }
 
    // Otherwise, find its correct position
    else {
        int pos = lower_bound(ans.begin(),
                              ans.end(),
                              num)
                  - ans.begin();
 
        // Insert the element
        ans.insert(ans.begin() + pos,
                   num);
    }
}
 
// Function to print the sorted stream of integers
void sortStream(int arr[], int N)
{
    // Stores the sorted stream of integers
    vector ans;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Function Call
        Sort(ans, arr[i]);
 
        // Print the array after
        // every insertion
        for (int i = 0; i < ans.size(); i++) {
            cout << ans[i] << " ";
        }
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 1, 7, 6, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    sortStream(arr, N);
 
    return 0;
}
输出:
4 
1 4 
1 4 7 
1 4 6 7 
1 2 4 6 7

时间复杂度: O(N*log N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live