Question

Write a program that generate 50,000 random integers (range: 1 through 50,000,000), have these random numbers...

Write a program that generate 50,000 random integers (range: 1 through 50,000,000), have these random numbers sorted and stored into a file. Requirement: - use dynamic memory for storing these numbers. - run insertion sort algorithm to sort this array. - store sorted numbers into a file. File name: sorted.txt

should be done inC++

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find properly commented and working code below :
------------------------------------------------------------------

#include<bits/stdc++.h>
using namespace std;
void insertionSortMethod(vector<int> &array); //Declare method

int main(int argc, char const *argv[]){
   vector<int> array;
   int tmp;

   for (int i = 0; i < 50000; i++) { //Put random integers into
       tmp = (rand() % 50000000) + 1; //dynamic array
       array.push_back(tmp);
   }

   insertionSortMethod(array);       //sort the array

   ofstream outputFile;           //write the array contents
   outputFile.open ("sorted.txt");   //to sorted.txt

   printf("writing to file : sorted.txt " );
   for (int i = 0; i < 50000; i++) {
       outputFile << array[i] <<" ";
   }

   outputFile.close();
}

//standard insertion sort algorithm
void insertionSortMethod(vector<int> &array)
{
   int size = array.size();
   int q, pivot, p;
   for (q = 1; q < size; q++)
   {
       p = q-1;
       pivot = array[q];
       while(p >= 0 && array[p] > pivot){
           array[p+1] = array[p];
           p = p-1;
       }
       array[p+1] = pivot;
   }
}

------------------------------------------------------------------

Please find the screenshot for working code :

Add a comment
Know the answer?
Add Answer to:
Write a program that generate 50,000 random integers (range: 1 through 50,000,000), have these random numbers...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT