Sorting data in files: distribution of the initial series C++
Somethimes there are so many data in file to sort that PC just can't process, so you need such a algorithm as
this one. I used pyramid sorting (it's logarithm sotring).
#include "stdafx.h"
#include "iostream"
#include "stdio.h"
#include <fstream>
#include <ctime>
using namespace std;
void sift( int *array, int , int );
void generateRand(int n);
void heapsort( int *array, int );void main()
{
int i, size = 0;
int *array;
cout<<"Input number of elements to generate\n";
int N;
cin>>N;
generateRand(N);
//if you don't know how many elemets are in text file
ifstream fin("file_input.txt");
while(!fin.eof())
{
fin>>i;
++size;
}
fin.close();
size--;
cout << "Number of elements: \n ";
cout << size<<"\n";
array = new int[size];
i = 0;
ifstream fin2("file_input.txt");
while(!fin2.eof())
{
fin2>>array[i];
i++;
}
fin2.close();
heapsort( array, size );
cout<<"\nResultes are in file_out.txt\n";
}
void sift( int *array, int L, int R )
{
int i, j;
int item;
i = L;
j = 2*L;
item = array[L];
if ( j < R && array[j] < array[j + 1] ) j++;
while ( j <= R && item < array[j] )
{
array[i] = array[j];
i = j;
j = 2*j;
if ( j < R && array[j] < array[j + 1] ) j++;
}
array[i] = item;
}
void heapsort( int *array, int size )
{
ofstream fout2("file_out.txt");
int sort=0;
int L, R;
int item;
L = size/2;
R = size - 1;
while ( L > 0 )
{
L--;
sift( array, L, R );
++sort;
}
fout2<<array[0]<<" ";
while ( R > 0 )
{
item = array[0];
array[0] = array[R];
array[R] = item;
R--;
sift( array, L, R );
fout2<<array[L]<<" ";
++sort;
}
fout2.close();
cout<<"\nf: "<<sort;
}
// generating numbers in file
void generateRand(int n)
{
ofstream fout("file_input.txt");
srand ( time(NULL) );
int temp;
for(int i = 0; i<n; i++)
{
temp = rand() % 200;
fout<<temp<<" ";
}
fout.close();
cout<<"Generating completed\n";
}
No comments:
Post a Comment