SlideShare a Scribd company logo
Write a program that obtains the execution time of selection sort, bubble sort, merge sort, quick
sort, heap sort, and radix sort for input size 50,000, 100,000, 150,000, 200,000, 250,000, and
300,000. Your program should create data randomly and print a table as shown in the following
sample run: long startTime System. nanoTime(); perform the task; long endTime = System.
nanoTime(); long executionTime = endTime - startTime;
Solution
Hello there,
please find attached code and it's output.I have printed intermediate SYSOUT. You can remove
those. It takes a bit longer time so wait for the final output! :-)
====O/P====
|Array |Selection |Insertion |Bubble |Merge |Quick |Radix |
|Size |Sort |Sort |Sort |Sort |Sort |Sort |
--------------------------------------------------------------------------------------------------------------------
--------------------------------
|50000 |855 |796 |2821 |16 |18 |21 |
|100000 |3482 |3243 |11422 |16 |0 |16 |
|150000 |7897 |7569 |26628 |25 |10 |7 |
|200000 |13683 |13360 |46701 |33 |10 |0 |
=====CODE=====
import java.util.Arrays;
import java.util.Random;
public class SortingAlgoPerformanceMeasurement {
static int[] size = { 50000, 100000, 150000, 200000 };
static String format = "|%1$-20s|%2$-20s|%3$-20s|%4$-20s|%5$-20s|%6$-20s|%7$-20s| ";
public static void main(String args[]) {
int max = 5000;
long startTime, endTime, executionTime;
long[][] time = new long[size.length][6];
Random generator = new Random();
for (int i = 0; i < size.length; i++) { // For getting size of different
int indexForAlgo = 0;
// array to be created
int[] array = new int[size[i]];
int[] unSortedArray = new int[size[i]];
for (int j = 0; j < size[i]; j++) { // For creating that many random
// numbers.
array[j] = generator.nextInt(max); // Prepare an array for all
// size
}
System.out.println("Unsorted array of length: " + array.length + " ");
System.out.println(Arrays.toString(array));
System.arraycopy(array, 0, unSortedArray, 0, size[i]); // Retaining
// the copy
// of
// unsorted
// array
startTime = System.currentTimeMillis();
selectionSort(array);
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
time[i][indexForAlgo] = executionTime;
indexForAlgo++;
System.out.println("O/P:selectionSort");
System.out.println(Arrays.toString(array));
System.arraycopy(unSortedArray, 0, array, 0, size[i]); // Again
// make
// it
// unsorted
//if (array.length != 100000 && array.length != 200000) {
startTime = System.currentTimeMillis();
insertionSort(array);
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
time[i][indexForAlgo] = executionTime;
System.out.println("O/P:insertionSort");
System.out.println(Arrays.toString(array));
System.arraycopy(unSortedArray, 0, array, 0, size[i]);
//}
indexForAlgo++;
startTime = System.currentTimeMillis();
bubbleSort(array);
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
time[i][indexForAlgo] = executionTime;
indexForAlgo++;
System.out.println("O/P:bubbleSort");
System.out.println(Arrays.toString(array));
System.arraycopy(unSortedArray, 0, array, 0, size[i]);
//if (array.length != 100000 && array.length != 200000) {
startTime = System.currentTimeMillis();
mergeSort(array);
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
time[i][indexForAlgo] = executionTime;
System.out.println("O/P:mergeSort");
System.out.println(Arrays.toString(array));
System.arraycopy(unSortedArray, 0, array, 0, size[i]);
//}
indexForAlgo++;
//if (array.length != 100000 && array.length != 200000) {
startTime = System.currentTimeMillis();
quickSort(array, 0, array.length - 1);
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
time[i][indexForAlgo] = executionTime;
System.out.println("O/P:quickSort");
System.out.println(Arrays.toString(array));
System.arraycopy(unSortedArray, 0, array, 0, size[i]);
//}
indexForAlgo++;
// unsorted
startTime = System.currentTimeMillis();
radixSort(array);
endTime = System.currentTimeMillis();
executionTime = endTime - startTime;
time[i][indexForAlgo] = executionTime;
indexForAlgo++;
System.out.println("O/P:radixSort");
System.out.println(Arrays.toString(array));
System.arraycopy(unSortedArray, 0, array, 0, size[i]);
}
// Print table.
printInTabularFormat(time);
}
/**
* Implements Selection Sort.
*
* @param arr
*/
public static void selectionSort(int arr[]) {
int N = arr.length;
int i, j, pos, temp;
for (i = 0; i < N - 1; i++) {
pos = i;
for (j = i + 1; j < N; j++) {
if (arr[j] < arr[pos]) {
pos = j;
}
}
/* Swap arr[i] and arr[pos] */
temp = arr[i];
arr[i] = arr[pos];
arr[pos] = temp;
}
}
/**
* Implements Insertion Sort.
*
* @param arr
*/
public static void insertionSort(int[] arr) {
int temp;
for (int i = 1; i < arr.length; i++) {
for (int j = i; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
/**
* Implements Bubble Sort.
*
* @param arr
*/
public static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (arr[j - 1] > arr[j]) {
// swap the elements!
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}
/**
* Implements Merge Sort.
*
* @param arr
*/
public static void mergeSort(int[] arr) {
if (arr.length <= 1) {
return;
}
// Split the array in half
int[] first = new int[arr.length / 2];
int[] second = new int[arr.length - first.length];
System.arraycopy(arr, 0, first, 0, first.length);
System.arraycopy(arr, first.length, second, 0, second.length);
// Sort each half
mergeSort(first);
mergeSort(second);
// Merge the halves together, overwriting the original array
merge(first, second, arr);
}
private static void merge(int[] first, int[] second, int[] result) {
// Merge both halves into the result array
// Next element to consider in the first array
int iFirst = 0;
// Next element to consider in the second array
int iSecond = 0;
// Next open position in the result
int j = 0;
// As long as neither iFirst nor iSecond is past the end, move the
// smaller element into the result.
while (iFirst < first.length && iSecond < second.length) {
if (first[iFirst] < second[iSecond]) {
result[j] = first[iFirst];
iFirst++;
} else {
result[j] = second[iSecond];
iSecond++;
}
j++;
}
// copy what's left
System.arraycopy(first, iFirst, result, j, first.length - iFirst);
System.arraycopy(second, iSecond, result, j, second.length - iSecond);
}
/**
* Implements Quick Sort.
*
* @param arr
*/
public static void quickSort(int[] arr, int low, int high) {
if (arr == null | arr.length == 0)
return;
if (low >= high)
return;
// pick the pivot
int middle = low + (high - low) / 2;
int pivot = arr[middle];
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}
private static int getMax(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
// A function to do counting sort of arr[] according to
// the digit represented by exp.
private static void countSort(int arr[], int n, int exp) {
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count, 0);
// Store count of occurrences in count[]
for (i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;
// Change count[i] so that count[i] now contains
// actual position of this digit in output[]
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
// Copy the output array to arr[], so that arr[] now
// contains sorted numbers according to curent digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}
/**
* Implements Radix Sort.
*
* @param arr
*/
static void radixSort(int arr[]) {
// Find the maximum number to know number of digits
int m = getMax(arr, arr.length);
// Do counting sort for every digit. Note that instead
// of passing digit number, exp is passed. exp is 10^i
// where i is current digit number
for (int exp = 1; m / exp > 0; exp *= 10)
countSort(arr, arr.length, exp);
}
public static void printInTabularFormat(long[][] time) {
System.out.println(" ");
System.out.format(format, "Array", "Selection", "Insertion", "Bubble", "Merge",
"Quick", "Radix");
System.out.format(format, "Size", "Sort", "Sort", "Sort", "Sort", "Sort", "Sort");
System.out
.println("---------------------------------------------------------------------------------------------
-------------------------------------------------------");
int sizeIndex = 0;
for (long[] arr : time) {
System.out.format(format, size[sizeIndex], arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]);
sizeIndex++;
}
}
}
===
Let me know if you have any doubts.
Thanks.

More Related Content

Similar to Write a program that obtains the execution time of selection sort, bu.pdf

please help finish sorting methods- import java-util-Arrays- import ja.pdf
please help finish sorting methods- import java-util-Arrays- import ja.pdfplease help finish sorting methods- import java-util-Arrays- import ja.pdf
please help finish sorting methods- import java-util-Arrays- import ja.pdf
anfenterprises
 
import java-util-Arrays- import java-io-PrintWriter- import java-io-Fi.pdf
import java-util-Arrays- import java-io-PrintWriter- import java-io-Fi.pdfimport java-util-Arrays- import java-io-PrintWriter- import java-io-Fi.pdf
import java-util-Arrays- import java-io-PrintWriter- import java-io-Fi.pdf
adhityalapcare
 
I need to find run time analysis and description of the algo.pdf
I need to find run time analysis and description of the algo.pdfI need to find run time analysis and description of the algo.pdf
I need to find run time analysis and description of the algo.pdf
aakashenterprises
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
piyush Kumar Sharma
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
HimanshuKansal22
 
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfHi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
anujsharmaanuj14
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
yamew16788
 
Merge Sort java with a few details, please include comments if possi.pdf
Merge Sort java with a few details, please include comments if possi.pdfMerge Sort java with a few details, please include comments if possi.pdf
Merge Sort java with a few details, please include comments if possi.pdf
feelinggifts
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
Intro C# Book
 
2DArrays.ppt
2DArrays.ppt2DArrays.ppt
2DArrays.ppt
Nooryaseen9
 
Example of JAVA Program
Example of JAVA ProgramExample of JAVA Program
Example of JAVA ProgramTrenton Asbury
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
shafat6712
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
The purpose of this C++ programming project is to allow the student .pdf
The purpose of this C++ programming project is to allow the student .pdfThe purpose of this C++ programming project is to allow the student .pdf
The purpose of this C++ programming project is to allow the student .pdf
Rahul04August
 
SP-First-Lecture.ppt
SP-First-Lecture.pptSP-First-Lecture.ppt
SP-First-Lecture.ppt
FareedIhsas
 
#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx
ajoy21
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
YOGESH SINGH
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structureSaad Gabr
 

Similar to Write a program that obtains the execution time of selection sort, bu.pdf (20)

please help finish sorting methods- import java-util-Arrays- import ja.pdf
please help finish sorting methods- import java-util-Arrays- import ja.pdfplease help finish sorting methods- import java-util-Arrays- import ja.pdf
please help finish sorting methods- import java-util-Arrays- import ja.pdf
 
import java-util-Arrays- import java-io-PrintWriter- import java-io-Fi.pdf
import java-util-Arrays- import java-io-PrintWriter- import java-io-Fi.pdfimport java-util-Arrays- import java-io-PrintWriter- import java-io-Fi.pdf
import java-util-Arrays- import java-io-PrintWriter- import java-io-Fi.pdf
 
I need to find run time analysis and description of the algo.pdf
I need to find run time analysis and description of the algo.pdfI need to find run time analysis and description of the algo.pdf
I need to find run time analysis and description of the algo.pdf
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdfHi, Please find my codeimport java.util.Random;public class Pro.pdf
Hi, Please find my codeimport java.util.Random;public class Pro.pdf
 
C++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdfC++ Nested loops, matrix and fuctions.pdf
C++ Nested loops, matrix and fuctions.pdf
 
Merge Sort java with a few details, please include comments if possi.pdf
Merge Sort java with a few details, please include comments if possi.pdfMerge Sort java with a few details, please include comments if possi.pdf
Merge Sort java with a few details, please include comments if possi.pdf
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
2DArrays.ppt
2DArrays.ppt2DArrays.ppt
2DArrays.ppt
 
Example of JAVA Program
Example of JAVA ProgramExample of JAVA Program
Example of JAVA Program
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
The purpose of this C++ programming project is to allow the student .pdf
The purpose of this C++ programming project is to allow the student .pdfThe purpose of this C++ programming project is to allow the student .pdf
The purpose of this C++ programming project is to allow the student .pdf
 
SP-First-Lecture.ppt
SP-First-Lecture.pptSP-First-Lecture.ppt
SP-First-Lecture.ppt
 
#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx#include stdafx.h using namespace std; #include stdlib.h.docx
#include stdafx.h using namespace std; #include stdlib.h.docx
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Lec2&3_DataStructure
Lec2&3_DataStructureLec2&3_DataStructure
Lec2&3_DataStructure
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
Lec2
Lec2Lec2
Lec2
 

More from arri2009av

Identify five muscles of the head area that have a name that is very .pdf
Identify five muscles of the head area that have a name that is very .pdfIdentify five muscles of the head area that have a name that is very .pdf
Identify five muscles of the head area that have a name that is very .pdf
arri2009av
 
Identify non-neoplastic conditions effecting pregnancy. Describe STI.pdf
Identify non-neoplastic conditions effecting pregnancy. Describe STI.pdfIdentify non-neoplastic conditions effecting pregnancy. Describe STI.pdf
Identify non-neoplastic conditions effecting pregnancy. Describe STI.pdf
arri2009av
 
From a mixed field, what is easier to facilitate through artificial s.pdf
From a mixed field, what is easier to facilitate through artificial s.pdfFrom a mixed field, what is easier to facilitate through artificial s.pdf
From a mixed field, what is easier to facilitate through artificial s.pdf
arri2009av
 
Explain how you would tell if something that looks like a leaf (flat.pdf
Explain how you would tell if something that looks like a leaf (flat.pdfExplain how you would tell if something that looks like a leaf (flat.pdf
Explain how you would tell if something that looks like a leaf (flat.pdf
arri2009av
 
Explain what a standard deviation value measures in quantitative dat.pdf
Explain what a standard deviation value measures in quantitative dat.pdfExplain what a standard deviation value measures in quantitative dat.pdf
Explain what a standard deviation value measures in quantitative dat.pdf
arri2009av
 
Einstein, in his famous photoelectric effect experiment demonstr.pdf
Einstein, in his famous photoelectric effect experiment demonstr.pdfEinstein, in his famous photoelectric effect experiment demonstr.pdf
Einstein, in his famous photoelectric effect experiment demonstr.pdf
arri2009av
 
Contrast autochthonous and allochthonous food webs. Which type would.pdf
Contrast autochthonous and allochthonous food webs. Which type would.pdfContrast autochthonous and allochthonous food webs. Which type would.pdf
Contrast autochthonous and allochthonous food webs. Which type would.pdf
arri2009av
 
Based on the below and using the 12 categories of threats identify 3 .pdf
Based on the below and using the 12 categories of threats identify 3 .pdfBased on the below and using the 12 categories of threats identify 3 .pdf
Based on the below and using the 12 categories of threats identify 3 .pdf
arri2009av
 
Blair, R. B. 1996. Land use and avian species diversity along an urb.pdf
Blair, R. B. 1996. Land use and avian species diversity along an urb.pdfBlair, R. B. 1996. Land use and avian species diversity along an urb.pdf
Blair, R. B. 1996. Land use and avian species diversity along an urb.pdf
arri2009av
 
An attack in which an authentic-looking e-mail or website entices a .pdf
An attack in which an authentic-looking e-mail or website entices a .pdfAn attack in which an authentic-looking e-mail or website entices a .pdf
An attack in which an authentic-looking e-mail or website entices a .pdf
arri2009av
 
Consider a relation T with six attributes ABCDEF where AB is a compo.pdf
Consider a relation T with six attributes ABCDEF where AB is a compo.pdfConsider a relation T with six attributes ABCDEF where AB is a compo.pdf
Consider a relation T with six attributes ABCDEF where AB is a compo.pdf
arri2009av
 
A vague appointment Four people make an appointment to meet each ot.pdf
A vague appointment Four people make an appointment to meet each ot.pdfA vague appointment Four people make an appointment to meet each ot.pdf
A vague appointment Four people make an appointment to meet each ot.pdf
arri2009av
 
Assume real numbers R for now. Consider relation on R, x y iff x .pdf
Assume real numbers R for now. Consider relation  on R, x  y iff x  .pdfAssume real numbers R for now. Consider relation  on R, x  y iff x  .pdf
Assume real numbers R for now. Consider relation on R, x y iff x .pdf
arri2009av
 
An enzyme aggase requires 16 units of activity for wild type functio.pdf
An enzyme aggase requires 16 units of activity for wild type functio.pdfAn enzyme aggase requires 16 units of activity for wild type functio.pdf
An enzyme aggase requires 16 units of activity for wild type functio.pdf
arri2009av
 
17. Of these, which represents a heterozygote a. aa b. Ab c. .pdf
17. Of these, which represents a heterozygote a. aa b. Ab c. .pdf17. Of these, which represents a heterozygote a. aa b. Ab c. .pdf
17. Of these, which represents a heterozygote a. aa b. Ab c. .pdf
arri2009av
 
1. Match the decription listed with the corresponding structureA. .pdf
1. Match the decription listed with the corresponding structureA. .pdf1. Match the decription listed with the corresponding structureA. .pdf
1. Match the decription listed with the corresponding structureA. .pdf
arri2009av
 
1.) What are some factors that should be taken into account when est.pdf
1.) What are some factors that should be taken into account when est.pdf1.) What are some factors that should be taken into account when est.pdf
1.) What are some factors that should be taken into account when est.pdf
arri2009av
 
Write a program that asks the user for the name of a file. The progr.pdf
Write a program that asks the user for the name of a file. The progr.pdfWrite a program that asks the user for the name of a file. The progr.pdf
Write a program that asks the user for the name of a file. The progr.pdf
arri2009av
 
Wings of bats area. Plesiomorphic (ancestral) feature for mammals.pdf
Wings of bats area. Plesiomorphic (ancestral) feature for mammals.pdfWings of bats area. Plesiomorphic (ancestral) feature for mammals.pdf
Wings of bats area. Plesiomorphic (ancestral) feature for mammals.pdf
arri2009av
 
Why do financial assets show up as component of household wealth.pdf
Why do financial assets show up as component of household wealth.pdfWhy do financial assets show up as component of household wealth.pdf
Why do financial assets show up as component of household wealth.pdf
arri2009av
 

More from arri2009av (20)

Identify five muscles of the head area that have a name that is very .pdf
Identify five muscles of the head area that have a name that is very .pdfIdentify five muscles of the head area that have a name that is very .pdf
Identify five muscles of the head area that have a name that is very .pdf
 
Identify non-neoplastic conditions effecting pregnancy. Describe STI.pdf
Identify non-neoplastic conditions effecting pregnancy. Describe STI.pdfIdentify non-neoplastic conditions effecting pregnancy. Describe STI.pdf
Identify non-neoplastic conditions effecting pregnancy. Describe STI.pdf
 
From a mixed field, what is easier to facilitate through artificial s.pdf
From a mixed field, what is easier to facilitate through artificial s.pdfFrom a mixed field, what is easier to facilitate through artificial s.pdf
From a mixed field, what is easier to facilitate through artificial s.pdf
 
Explain how you would tell if something that looks like a leaf (flat.pdf
Explain how you would tell if something that looks like a leaf (flat.pdfExplain how you would tell if something that looks like a leaf (flat.pdf
Explain how you would tell if something that looks like a leaf (flat.pdf
 
Explain what a standard deviation value measures in quantitative dat.pdf
Explain what a standard deviation value measures in quantitative dat.pdfExplain what a standard deviation value measures in quantitative dat.pdf
Explain what a standard deviation value measures in quantitative dat.pdf
 
Einstein, in his famous photoelectric effect experiment demonstr.pdf
Einstein, in his famous photoelectric effect experiment demonstr.pdfEinstein, in his famous photoelectric effect experiment demonstr.pdf
Einstein, in his famous photoelectric effect experiment demonstr.pdf
 
Contrast autochthonous and allochthonous food webs. Which type would.pdf
Contrast autochthonous and allochthonous food webs. Which type would.pdfContrast autochthonous and allochthonous food webs. Which type would.pdf
Contrast autochthonous and allochthonous food webs. Which type would.pdf
 
Based on the below and using the 12 categories of threats identify 3 .pdf
Based on the below and using the 12 categories of threats identify 3 .pdfBased on the below and using the 12 categories of threats identify 3 .pdf
Based on the below and using the 12 categories of threats identify 3 .pdf
 
Blair, R. B. 1996. Land use and avian species diversity along an urb.pdf
Blair, R. B. 1996. Land use and avian species diversity along an urb.pdfBlair, R. B. 1996. Land use and avian species diversity along an urb.pdf
Blair, R. B. 1996. Land use and avian species diversity along an urb.pdf
 
An attack in which an authentic-looking e-mail or website entices a .pdf
An attack in which an authentic-looking e-mail or website entices a .pdfAn attack in which an authentic-looking e-mail or website entices a .pdf
An attack in which an authentic-looking e-mail or website entices a .pdf
 
Consider a relation T with six attributes ABCDEF where AB is a compo.pdf
Consider a relation T with six attributes ABCDEF where AB is a compo.pdfConsider a relation T with six attributes ABCDEF where AB is a compo.pdf
Consider a relation T with six attributes ABCDEF where AB is a compo.pdf
 
A vague appointment Four people make an appointment to meet each ot.pdf
A vague appointment Four people make an appointment to meet each ot.pdfA vague appointment Four people make an appointment to meet each ot.pdf
A vague appointment Four people make an appointment to meet each ot.pdf
 
Assume real numbers R for now. Consider relation on R, x y iff x .pdf
Assume real numbers R for now. Consider relation  on R, x  y iff x  .pdfAssume real numbers R for now. Consider relation  on R, x  y iff x  .pdf
Assume real numbers R for now. Consider relation on R, x y iff x .pdf
 
An enzyme aggase requires 16 units of activity for wild type functio.pdf
An enzyme aggase requires 16 units of activity for wild type functio.pdfAn enzyme aggase requires 16 units of activity for wild type functio.pdf
An enzyme aggase requires 16 units of activity for wild type functio.pdf
 
17. Of these, which represents a heterozygote a. aa b. Ab c. .pdf
17. Of these, which represents a heterozygote a. aa b. Ab c. .pdf17. Of these, which represents a heterozygote a. aa b. Ab c. .pdf
17. Of these, which represents a heterozygote a. aa b. Ab c. .pdf
 
1. Match the decription listed with the corresponding structureA. .pdf
1. Match the decription listed with the corresponding structureA. .pdf1. Match the decription listed with the corresponding structureA. .pdf
1. Match the decription listed with the corresponding structureA. .pdf
 
1.) What are some factors that should be taken into account when est.pdf
1.) What are some factors that should be taken into account when est.pdf1.) What are some factors that should be taken into account when est.pdf
1.) What are some factors that should be taken into account when est.pdf
 
Write a program that asks the user for the name of a file. The progr.pdf
Write a program that asks the user for the name of a file. The progr.pdfWrite a program that asks the user for the name of a file. The progr.pdf
Write a program that asks the user for the name of a file. The progr.pdf
 
Wings of bats area. Plesiomorphic (ancestral) feature for mammals.pdf
Wings of bats area. Plesiomorphic (ancestral) feature for mammals.pdfWings of bats area. Plesiomorphic (ancestral) feature for mammals.pdf
Wings of bats area. Plesiomorphic (ancestral) feature for mammals.pdf
 
Why do financial assets show up as component of household wealth.pdf
Why do financial assets show up as component of household wealth.pdfWhy do financial assets show up as component of household wealth.pdf
Why do financial assets show up as component of household wealth.pdf
 

Recently uploaded

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 

Recently uploaded (20)

Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 

Write a program that obtains the execution time of selection sort, bu.pdf

  • 1. Write a program that obtains the execution time of selection sort, bubble sort, merge sort, quick sort, heap sort, and radix sort for input size 50,000, 100,000, 150,000, 200,000, 250,000, and 300,000. Your program should create data randomly and print a table as shown in the following sample run: long startTime System. nanoTime(); perform the task; long endTime = System. nanoTime(); long executionTime = endTime - startTime; Solution Hello there, please find attached code and it's output.I have printed intermediate SYSOUT. You can remove those. It takes a bit longer time so wait for the final output! :-) ====O/P==== |Array |Selection |Insertion |Bubble |Merge |Quick |Radix | |Size |Sort |Sort |Sort |Sort |Sort |Sort | -------------------------------------------------------------------------------------------------------------------- -------------------------------- |50000 |855 |796 |2821 |16 |18 |21 | |100000 |3482 |3243 |11422 |16 |0 |16 | |150000 |7897 |7569 |26628 |25 |10 |7 | |200000 |13683 |13360 |46701 |33 |10 |0 | =====CODE===== import java.util.Arrays; import java.util.Random; public class SortingAlgoPerformanceMeasurement { static int[] size = { 50000, 100000, 150000, 200000 }; static String format = "|%1$-20s|%2$-20s|%3$-20s|%4$-20s|%5$-20s|%6$-20s|%7$-20s| "; public static void main(String args[]) { int max = 5000; long startTime, endTime, executionTime; long[][] time = new long[size.length][6]; Random generator = new Random(); for (int i = 0; i < size.length; i++) { // For getting size of different int indexForAlgo = 0; // array to be created int[] array = new int[size[i]];
  • 2. int[] unSortedArray = new int[size[i]]; for (int j = 0; j < size[i]; j++) { // For creating that many random // numbers. array[j] = generator.nextInt(max); // Prepare an array for all // size } System.out.println("Unsorted array of length: " + array.length + " "); System.out.println(Arrays.toString(array)); System.arraycopy(array, 0, unSortedArray, 0, size[i]); // Retaining // the copy // of // unsorted // array startTime = System.currentTimeMillis(); selectionSort(array); endTime = System.currentTimeMillis(); executionTime = endTime - startTime; time[i][indexForAlgo] = executionTime; indexForAlgo++; System.out.println("O/P:selectionSort"); System.out.println(Arrays.toString(array)); System.arraycopy(unSortedArray, 0, array, 0, size[i]); // Again // make // it // unsorted //if (array.length != 100000 && array.length != 200000) { startTime = System.currentTimeMillis(); insertionSort(array); endTime = System.currentTimeMillis(); executionTime = endTime - startTime; time[i][indexForAlgo] = executionTime; System.out.println("O/P:insertionSort"); System.out.println(Arrays.toString(array)); System.arraycopy(unSortedArray, 0, array, 0, size[i]); //} indexForAlgo++;
  • 3. startTime = System.currentTimeMillis(); bubbleSort(array); endTime = System.currentTimeMillis(); executionTime = endTime - startTime; time[i][indexForAlgo] = executionTime; indexForAlgo++; System.out.println("O/P:bubbleSort"); System.out.println(Arrays.toString(array)); System.arraycopy(unSortedArray, 0, array, 0, size[i]); //if (array.length != 100000 && array.length != 200000) { startTime = System.currentTimeMillis(); mergeSort(array); endTime = System.currentTimeMillis(); executionTime = endTime - startTime; time[i][indexForAlgo] = executionTime; System.out.println("O/P:mergeSort"); System.out.println(Arrays.toString(array)); System.arraycopy(unSortedArray, 0, array, 0, size[i]); //} indexForAlgo++; //if (array.length != 100000 && array.length != 200000) { startTime = System.currentTimeMillis(); quickSort(array, 0, array.length - 1); endTime = System.currentTimeMillis(); executionTime = endTime - startTime; time[i][indexForAlgo] = executionTime; System.out.println("O/P:quickSort"); System.out.println(Arrays.toString(array)); System.arraycopy(unSortedArray, 0, array, 0, size[i]); //} indexForAlgo++; // unsorted startTime = System.currentTimeMillis(); radixSort(array); endTime = System.currentTimeMillis(); executionTime = endTime - startTime;
  • 4. time[i][indexForAlgo] = executionTime; indexForAlgo++; System.out.println("O/P:radixSort"); System.out.println(Arrays.toString(array)); System.arraycopy(unSortedArray, 0, array, 0, size[i]); } // Print table. printInTabularFormat(time); } /** * Implements Selection Sort. * * @param arr */ public static void selectionSort(int arr[]) { int N = arr.length; int i, j, pos, temp; for (i = 0; i < N - 1; i++) { pos = i; for (j = i + 1; j < N; j++) { if (arr[j] < arr[pos]) { pos = j; } } /* Swap arr[i] and arr[pos] */ temp = arr[i]; arr[i] = arr[pos]; arr[pos] = temp; } } /** * Implements Insertion Sort. * * @param arr */ public static void insertionSort(int[] arr) {
  • 5. int temp; for (int i = 1; i < arr.length; i++) { for (int j = i; j > 0; j--) { if (arr[j] < arr[j - 1]) { temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } } } } /** * Implements Bubble Sort. * * @param arr */ public static void bubbleSort(int[] arr) { int n = arr.length; int temp = 0; for (int i = 0; i < n; i++) { for (int j = 1; j < (n - i); j++) { if (arr[j - 1] > arr[j]) { // swap the elements! temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp; } } } } /** * Implements Merge Sort. * * @param arr */ public static void mergeSort(int[] arr) {
  • 6. if (arr.length <= 1) { return; } // Split the array in half int[] first = new int[arr.length / 2]; int[] second = new int[arr.length - first.length]; System.arraycopy(arr, 0, first, 0, first.length); System.arraycopy(arr, first.length, second, 0, second.length); // Sort each half mergeSort(first); mergeSort(second); // Merge the halves together, overwriting the original array merge(first, second, arr); } private static void merge(int[] first, int[] second, int[] result) { // Merge both halves into the result array // Next element to consider in the first array int iFirst = 0; // Next element to consider in the second array int iSecond = 0; // Next open position in the result int j = 0; // As long as neither iFirst nor iSecond is past the end, move the // smaller element into the result. while (iFirst < first.length && iSecond < second.length) { if (first[iFirst] < second[iSecond]) { result[j] = first[iFirst]; iFirst++; } else { result[j] = second[iSecond]; iSecond++; } j++; } // copy what's left System.arraycopy(first, iFirst, result, j, first.length - iFirst);
  • 7. System.arraycopy(second, iSecond, result, j, second.length - iSecond); } /** * Implements Quick Sort. * * @param arr */ public static void quickSort(int[] arr, int low, int high) { if (arr == null | arr.length == 0) return; if (low >= high) return; // pick the pivot int middle = low + (high - low) / 2; int pivot = arr[middle]; // make left < pivot and right > pivot int i = low, j = high; while (i <= j) { while (arr[i] < pivot) { i++; } while (arr[j] > pivot) { j--; } if (i <= j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; } } // recursively sort two sub parts if (low < j) quickSort(arr, low, j); if (high > i)
  • 8. quickSort(arr, i, high); } private static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // A function to do counting sort of arr[] according to // the digit represented by exp. private static void countSort(int arr[], int n, int exp) { int output[] = new int[n]; // output array int i; int count[] = new int[10]; Arrays.fill(count, 0); // Store count of occurrences in count[] for (i = 0; i < n; i++) count[(arr[i] / exp) % 10]++; // Change count[i] so that count[i] now contains // actual position of this digit in output[] for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the output array for (i = n - 1; i >= 0; i--) { output[count[(arr[i] / exp) % 10] - 1] = arr[i]; count[(arr[i] / exp) % 10]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to curent digit for (i = 0; i < n; i++) arr[i] = output[i]; } /** * Implements Radix Sort. *
  • 9. * @param arr */ static void radixSort(int arr[]) { // Find the maximum number to know number of digits int m = getMax(arr, arr.length); // Do counting sort for every digit. Note that instead // of passing digit number, exp is passed. exp is 10^i // where i is current digit number for (int exp = 1; m / exp > 0; exp *= 10) countSort(arr, arr.length, exp); } public static void printInTabularFormat(long[][] time) { System.out.println(" "); System.out.format(format, "Array", "Selection", "Insertion", "Bubble", "Merge", "Quick", "Radix"); System.out.format(format, "Size", "Sort", "Sort", "Sort", "Sort", "Sort", "Sort"); System.out .println("--------------------------------------------------------------------------------------------- -------------------------------------------------------"); int sizeIndex = 0; for (long[] arr : time) { System.out.format(format, size[sizeIndex], arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]); sizeIndex++; } } } === Let me know if you have any doubts. Thanks.