0% found this document useful (0 votes)
14 views

Assignment 5

This document contains a C++ program to analyze the count sort algorithm. The program generates random arrays of integers, sorts them using count sort, and times the sorting process. It runs count sort on arrays of increasing sizes from 500,000 to 5,000,000 elements and outputs the array size and time taken for each run.

Uploaded by

Nilesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Assignment 5

This document contains a C++ program to analyze the count sort algorithm. The program generates random arrays of integers, sorts them using count sort, and times the sorting process. It runs count sort on arrays of increasing sizes from 500,000 to 5,000,000 elements and outputs the array size and time taken for each run.

Uploaded by

Nilesh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Assignment 5:

1. WAP for Analysis of the Count Sort.


Program:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <chrono>
#include <vector>

using namespace std;

void countSort(std::vector<int>& arr) {

int max_element = arr[0];


for (int i = 1; i < arr.size(); ++i) {
if (arr[i] > max_element) {
max_element = arr[i];
}
}

std::vector<int> count(max_element + 1, 0);

for (int i = 0; i < arr.size(); ++i) {


++count[arr[i]];
}

for (int i = 1; i <= max_element; ++i) {


count[i] += count[i - 1];
}

std::vector<int> output(arr.size());
for (int i = arr.size() - 1; i >= 0; --i) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}

for (int i = 0; i < arr.size(); ++i) {


arr[i] = output[i];
}
}

int main() {

clock_t start, end;

srand(time(0));
cout<<"index"<<": array size"<<", time taken in sec"<<endl;
for (int i = 0; i < 10; ++i) {
int arr_size = 500000 + i * 500000;
vector<int> arr(arr_size);

for (int j = 0; j < arr_size; ++j) {


arr[j] = rand() % 1000000000;
}

start = clock();
countSort(arr);
end = clock();

double time_taken = double(end - start) / CLOCKS_PER_SEC;


cout <<" "<< i + 1 << ": " << arr_size<<", " << time_taken<< endl;
}

return 0;
}
time ( sec)
0.3

0.251
0.25
0.219 0.221
0.205
0.2 0.189

0.15 0.142

0.11
0.1
0.078
0.06
0.05
0.015
0
500000 1000000 1500000 2000000 2500000 3000000 3500000 4000000 4500000 5000000

time ( sec)

You might also like