Search code examples
c++arrayssortinglarge-files

How to sort an array of order 300000?


I'm new to competitive programming and I came across ICPC Challenge on Codeforces. The first problem is https://codeforces.com/contest/1376/problem/A1 this and they gave file that has 30000 inputs. They basically ask you to sort list of integers in non-decreasing order.

I started off by implementing a bubble sort code and then gave the input file sort.in using freopen("sort.in","r",stdin) and then using freopen("output.out","w",stdout) function to create an output file. This worked fine for less inputs like 50-100 but when I gave the input file which has about 30000 inputs, the output file is empty. I did not understand why this happened.

I have two questions,

  1. which sorting algorithm to use?
  2. why the following code is not outputting the sorted array to output.out file?

link to the sort.in file: https://assets.codeforces.com/files/6f8518a9aaa619e7/sort.zip

here is my code:

#include <bits/stdc++.h>

using namespace std;

int main(){
    freopen("sort.in", "r", stdin);
    freopen("output.out", "w", stdout);
    int n, c, temp, arr[500000];
    cin >> n;
    c=n;

    for(int i=0; i<n; i++){
        cin >> arr[i];
    }

    while(n!=0){
        for(int i=0; i<n-1; i++){
            if(n)
            if(arr[i]>arr[i+1]){
                temp = arr[i+1];
                arr[i+1] = arr[i];
                arr[i] = temp;
            }
        }
        n=n-1;
    }

    for(int i=0; i<c; i++){
        cout << arr[i] << " ";
    }

    return 0;
}

Solution

  • You can manually implement Merge Sort algorithms. Or just call the built-in C++ sort function.

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main(){
        freopen("sort.in", "r", stdin);
        freopen("output.out", "w", stdout);
        int n, , arr[500000];
    
        cin >> n;
    
        for(int i=0; i<n; i++){
            cin >> arr[i];
        }
    
        sort( ar, ar + n ); 
    
        for(int i=0; i<n; i++){
            cout << arr[i] << " ";
        }
    
        return 0;
    }