SlideShare a Scribd company logo
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println("Usage: java OrderTest sizeOfArray "
+ "tor tjava OrderTest arrayFile");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println("unable to read array from " + args[0]);
System.exit(1);//14
}
}
System.out.println("before:");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(" after:");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + " ");
}
outFile.close();
} catch (IOException e) {
System.err.println("Could not write to " + outfile + " " + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) {
int myNum = 0;
for (int next = 1; next < array.length; next++) {//2
//n
myNum++;
int val = array[next];
int index = next;
while (index > 0 && val < array[index - 1]) {//3
array[index] = array[index - 1];//n
index--;
myNum++;
}
array[index] = val;
}
return myNum;
}
}
BieberSortTest.java
public class BieberSortTest {
public static void main(String[] args){
if (args.length != 1) {
System.out.println("Usage: java BieberSortTest numberOfBiebz");
System.exit(1);
}
try {
int n = Integer.parseInt(args[0]);
BieberSort bs = new BieberSort(n);
bs.printBiebers();
System.out.println("---------");
bs.sort(); // this is the method to measure
bs.printBiebers();
System.out.println(bs.getLoop1()+" <==Loop1");
System.out.println(bs.getLoop2()+" <==Loop");
} catch (NumberFormatException nfe) {
System.out.println("number of Biebz must be a positive integer");
nfe.printStackTrace();
}
}
}
BiberSort.java
import java.util.Random;
public class BieberSort {
private Biebz[] theBiebz;
int counterLoop1=0,counterLoop2=0;
/**
* Inner class for the BieberSort
*/
public class Biebz implements Comparable{
private int b;
public Biebz(int b){
this.b = b;
}
public int compareTo(Biebz o) {
return this.b - o.b;
}
public String toString() {
return String.valueOf(this.b);
}
}
/**
* Construct a new BieberSort class with n fans
*/
public BieberSort(int n) {
this.theBiebz = new Biebz[n];
Random rdm = new Random(System.currentTimeMillis());
for(int i = 0; i< n;i++){
theBiebz[i] = new Biebz(rdm.nextInt(n));
}
}
public int getLoop1(){
return counterLoop1;
}
public int getLoop2(){
return counterLoop2;
}
/**
* Prints all the Biebers that we have ...
*/
public void printBiebers(){
for(Biebz bz:theBiebz){
System.out.println(bz);
}
}
/**
* Sorts a collection of Bieber objects
*/
public void sort(){
for(int i =0;ii;j--){
counterLoop2++;
if(theBiebz[i].compareTo(theBiebz[j]) > 0 ){
swap(i,j);
}
}
}
}
private void swap(int i, int j){
Biebz b =theBiebz[i];
theBiebz[i] = theBiebz[j];
theBiebz[j]=b;
}
}
FindTest.java
public class FindTest {
/**
* Get an array of specified size and find the indexes of all elements
* in the array using Find.find().
*/
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FindTest sizeOfArray "
+ "tor tjava FindTest arrayFile");
System.exit(1);
}
// create or read the int[]
int size = 0;
int counter = 0;
int[] array = new int[0];
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println("unable to read array from " + args[0]);
System.exit(1);
}
}
// find the index of every element
double average=0;
for (int i = 1; i <= array.length; i++) {
//this is the method of interest, but you'll need to average
//the number of statements needed to find each element for
//meaningful results
int index = Find.find(array, i);
average = Find.getAverage(array);
System.out.printf("%d found at index %d ", i, index);
}
System.out.println("The average is: "+average);
System.out.println(size);
}
}
Find.java
public class Find {
/**
* Return index where value is found in array or -1 if not found.
*/
public static int find(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
public static double getAverage(int[] myArray){
int sum=0;
double average=0;
for (int i = 0; i < myArray.length; i++) {
sum=sum+myArray[i];
}
average=sum/myArray.length;
return average;
}
}
ConsecutivePairs.java
public class ConsecutivePairs {
private int n;
private long pairsCount;
private long numStatements = 0; //looking for the dominant section as n gets large
/**
* Generates all combinations of numberOfBits and counts all matched bit pairs.
*/
public ConsecutivePairs(int numberOfBits) throws IllegalArgumentException {
if (numberOfBits < 1) {
throw new IllegalArgumentException("number of bits must be positive");
}
n = numberOfBits;
pairsCount = 0;
int[] bit = new int[n];
for (int i = 0; i < bit.length; i++) {
bit[i] = 0;
}
//generate all combinations of n "bits" by mimicking a binary counter
while(positivesCount(bit) < n) {
numStatements++; //are these the most important statements?
//count "bits" that match their neighbor
for(int i = 0; i < bit.length - 1; i++) {
//numStatements++; //are these the most important statements?
if(bit[i] == bit[i+1]) {
pairsCount++;
}
}
//add 1
int b = 0;
while (b < bit.length && bit[b] == 1) {
bit[b] = 0;
b++;
//numStatements++; //are these the most important statements?
}
if (b < bit.length) {
bit[b] = 1;
}
}
//still need to count last state where all bits are 1s
//count "bits" that match their neighbor
for(int i = 0; i < bit.length - 1; i++) {
//numStatements++; //are these the most important statements?
if(bit[i] == bit[i+1]) {
pairsCount++;
}
}
}
private int positivesCount(int[] intsArray) {
int positives = 0;
for(int i = 0; i < intsArray.length; i++) {
//numStatements++; //are these the most important statements?
if(intsArray[i] > 0) {
positives++;
}
}
return positives;
}
public long getPairsCount() {
return pairsCount;
}
public int getNumberOfBits() {
return n;
}
public long getNumStatements() {
return numStatements;
}
}
ConsecutivePairsTest.java
public class ConsecutivePairsTest {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java ConsecutivePairsTest numberOfBits");
System.exit(1);
}
try {
int n = Integer.parseInt(args[0]);
ConsecutivePairs pairs = new ConsecutivePairs(n); //this is the call to measure
System.out.printf("for n = %d, there are %d matched bit pairs ",
n, pairs.getPairsCount());
System.out.printf("approximately %d statements were executed to calculate this
answer",
pairs.getNumStatements());
} catch (Exception nfe) {
System.out.println("number of bits must be a positive integer");
nfe.printStackTrace();
System.exit(1);
}
}
}
analysis.odt
Haseeb Nain
Computer Science 221
Mason Vail
FindSort:
Part 1 Section 1
Because this sort relies on finding a specific value at the within the array. And in doing so finds
multiple values at multiple points within the array it must be at least O(n). This is simply because
the amount of recursion is directly related to the size of the array.
Part 1 Section 2
Table 1 FindSort Data
FindSort
Input Average NumStatements
1000 500 500000
10000 5000 50000000
20000 10000 200000000
30000 15000 450000000
40000 20000 800000000
50000 25000 1250000000
Figure 1: FindSort Average
Figure 2: FindSort Statments
Part 1 Section 3
This outcome did not support my hypothesis, I believed that the array simply relied on the
length of the array, n, this is not the case. While the average was constant, the actual amount of
time the statements were run followed more closely to a O(n2).
Order Sort:
Part 2 Section 1
Because this sort relies on the value of a point in an array, and then compares the two arrays,
and then switches the position of the array based on its size in comparison, this sort will be
greater in magnitude than the previous FindSort. The order.java class seems to make the
comparison, so it must always run twice for each loop, the loop is the size of the array, so it will
repeat n times. When putting these together I arrive at a O(n2).
Part 2 Section 2
Table 2: OrderSort Data
OrderSort
Input NumStatements
1000 247753
10000 25256933
20000 1.00E+08
30000 2.24E+08
40000 3.98E+08
50000 6.23E+08
Figure 3: OrderSort Statements
Part 2 Section 3
After plotting the number of statements in relation to the number of inputs, I noticed that the
graph looked similar to the quadratic of the second power. This confirms my hypothesis of
O(n2).
BeiberSort:
Part 3 Section 1
BeiberSort is similar to Consecutive Sort, as it compares two values and then orders them from
lowest to greatest. Because it also follows though with two for loops, I believe this will also be
O(n2).
Part 3 Section 2
Table 3: BeiberSort Data
BeiberSort
Input Count
1000 499500
10000 49995000
20000 199990000
30000 449985000
40000 799980000
50000 1249975000
Figure 4: BeiberSort Statements
Part 3 Section 3
The information exracted from the amount of statements and the amount of inputs provides a
graph with a plot equivalent to a quadratic of power 2. This further confirms my hypothesis that
O(n2)
ConsecutiveSort:
Part 4 Section 1
Because the consecutive sort merges concepts from the previous sorting methods, I believe its
number of statements run must be larger then anything before. The consecutive sort will find
values, then compare the values and report values where two values are equivalent and
consecutive. The use of a while loop will also contribute to the amount of statements run,
because it directly relates to the size of “n”. In the end I believe this to be an exponential
increase, so O(2n).
Part 4 Section 2
Table 4: ConsecutiveSort Data
ConsecutiveSort
Input NumStatements
5 31
10 1023
15 32767
20 1048575
25 33554431
Figure 5: ConsecutiveSort Statements
Part 4 Section 3
The information provided by the input and the number of statements further confirms my
hypothesis. The slope was minimal at first by begins to ramp up significantly after 20. On my
excel sheet the data went negative for the value between 15 and 20, I believe this is simply an
error on the behalf of Excel.
Solution
OrderTest.java
public class OrderTest {
/**
* Get an array of specified size and pass it to Order.order().
* Report the results.
*/
public static void main(String[] args) {
if (args.length != 1) {//1
System.out.println("Usage: java OrderTest sizeOfArray "
+ "tor tjava OrderTest arrayFile");
System.exit(1);
}
// create or read the int[]
int size = 0;
int[] array = new int[0];//5
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {//8
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println("unable to read array from " + args[0]);
System.exit(1);//14
}
}
System.out.println("before:");//15
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);//1
}
int myNum = Order.order(array); //this is the call we want to measure
System.out.println(" after:");//18
for (int i = 0; i < array.length; i++) {//2 n
System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);
}
System.out.println(myNum);
}
}
ArrayOfInts.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayOfInts {
/**
* Returns an array of consecutive ints from 1 to size.
*/
public static int[] orderedArray(int size) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = i+1;
}
return a;
}
/**
* Returns a randomized array containing ints from 1 to size.
*/
public static int[] randomizedArray(int size) {
ArrayList aL = new ArrayList();
for (int i = 0; i < size; i++) {
aL.add(i+1);
}
Collections.shuffle(aL);
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = aL.get(i);
}
return a;
}
/**
* Writes an int[] to a plain-text file with ints separated by spaces.
* Useful for creating input files for repeatable tests.
*/
public static void arrayToFile(int[] array, String outfile) {
try {
FileWriter fw = new FileWriter(outfile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
for (int i : array) {
outFile.print(i + " ");
}
outFile.close();
} catch (IOException e) {
System.err.println("Could not write to " + outfile + " " + e);
}
}
/**
* Read ints from a file and return them in an int[]
*/
public static int[] arrayFromFile(String infile) throws FileNotFoundException,
InputMismatchException {
Scanner scan = new Scanner(new File(infile));
ArrayList aL = new ArrayList();
while (scan.hasNext()) {
aL.add(scan.nextInt());
}
scan.close();
int[] a = new int[aL.size()];
for (int i = 0; i < a.length; i++) {
a[i] = aL.get(i);
}
return a;
}
}
Order.java
public class Order {
/**
* Take an int[] and reorganize it so they are in ascending order.
*/
public static int order(int[] array) {
int myNum = 0;
for (int next = 1; next < array.length; next++) {//2
//n
myNum++;
int val = array[next];
int index = next;
while (index > 0 && val < array[index - 1]) {//3
array[index] = array[index - 1];//n
index--;
myNum++;
}
array[index] = val;
}
return myNum;
}
}
BieberSortTest.java
public class BieberSortTest {
public static void main(String[] args){
if (args.length != 1) {
System.out.println("Usage: java BieberSortTest numberOfBiebz");
System.exit(1);
}
try {
int n = Integer.parseInt(args[0]);
BieberSort bs = new BieberSort(n);
bs.printBiebers();
System.out.println("---------");
bs.sort(); // this is the method to measure
bs.printBiebers();
System.out.println(bs.getLoop1()+" <==Loop1");
System.out.println(bs.getLoop2()+" <==Loop");
} catch (NumberFormatException nfe) {
System.out.println("number of Biebz must be a positive integer");
nfe.printStackTrace();
}
}
}
BiberSort.java
import java.util.Random;
public class BieberSort {
private Biebz[] theBiebz;
int counterLoop1=0,counterLoop2=0;
/**
* Inner class for the BieberSort
*/
public class Biebz implements Comparable{
private int b;
public Biebz(int b){
this.b = b;
}
public int compareTo(Biebz o) {
return this.b - o.b;
}
public String toString() {
return String.valueOf(this.b);
}
}
/**
* Construct a new BieberSort class with n fans
*/
public BieberSort(int n) {
this.theBiebz = new Biebz[n];
Random rdm = new Random(System.currentTimeMillis());
for(int i = 0; i< n;i++){
theBiebz[i] = new Biebz(rdm.nextInt(n));
}
}
public int getLoop1(){
return counterLoop1;
}
public int getLoop2(){
return counterLoop2;
}
/**
* Prints all the Biebers that we have ...
*/
public void printBiebers(){
for(Biebz bz:theBiebz){
System.out.println(bz);
}
}
/**
* Sorts a collection of Bieber objects
*/
public void sort(){
for(int i =0;ii;j--){
counterLoop2++;
if(theBiebz[i].compareTo(theBiebz[j]) > 0 ){
swap(i,j);
}
}
}
}
private void swap(int i, int j){
Biebz b =theBiebz[i];
theBiebz[i] = theBiebz[j];
theBiebz[j]=b;
}
}
FindTest.java
public class FindTest {
/**
* Get an array of specified size and find the indexes of all elements
* in the array using Find.find().
*/
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java FindTest sizeOfArray "
+ "tor tjava FindTest arrayFile");
System.exit(1);
}
// create or read the int[]
int size = 0;
int counter = 0;
int[] array = new int[0];
try {
size = Integer.parseInt(args[0]);
array = ArrayOfInts.randomizedArray(size);
} catch (NumberFormatException nfe) {
try {
array = ArrayOfInts.arrayFromFile(args[0]);
size = array.length;
} catch (Exception e) {
System.err.println("unable to read array from " + args[0]);
System.exit(1);
}
}
// find the index of every element
double average=0;
for (int i = 1; i <= array.length; i++) {
//this is the method of interest, but you'll need to average
//the number of statements needed to find each element for
//meaningful results
int index = Find.find(array, i);
average = Find.getAverage(array);
System.out.printf("%d found at index %d ", i, index);
}
System.out.println("The average is: "+average);
System.out.println(size);
}
}
Find.java
public class Find {
/**
* Return index where value is found in array or -1 if not found.
*/
public static int find(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
public static double getAverage(int[] myArray){
int sum=0;
double average=0;
for (int i = 0; i < myArray.length; i++) {
sum=sum+myArray[i];
}
average=sum/myArray.length;
return average;
}
}
ConsecutivePairs.java
public class ConsecutivePairs {
private int n;
private long pairsCount;
private long numStatements = 0; //looking for the dominant section as n gets large
/**
* Generates all combinations of numberOfBits and counts all matched bit pairs.
*/
public ConsecutivePairs(int numberOfBits) throws IllegalArgumentException {
if (numberOfBits < 1) {
throw new IllegalArgumentException("number of bits must be positive");
}
n = numberOfBits;
pairsCount = 0;
int[] bit = new int[n];
for (int i = 0; i < bit.length; i++) {
bit[i] = 0;
}
//generate all combinations of n "bits" by mimicking a binary counter
while(positivesCount(bit) < n) {
numStatements++; //are these the most important statements?
//count "bits" that match their neighbor
for(int i = 0; i < bit.length - 1; i++) {
//numStatements++; //are these the most important statements?
if(bit[i] == bit[i+1]) {
pairsCount++;
}
}
//add 1
int b = 0;
while (b < bit.length && bit[b] == 1) {
bit[b] = 0;
b++;
//numStatements++; //are these the most important statements?
}
if (b < bit.length) {
bit[b] = 1;
}
}
//still need to count last state where all bits are 1s
//count "bits" that match their neighbor
for(int i = 0; i < bit.length - 1; i++) {
//numStatements++; //are these the most important statements?
if(bit[i] == bit[i+1]) {
pairsCount++;
}
}
}
private int positivesCount(int[] intsArray) {
int positives = 0;
for(int i = 0; i < intsArray.length; i++) {
//numStatements++; //are these the most important statements?
if(intsArray[i] > 0) {
positives++;
}
}
return positives;
}
public long getPairsCount() {
return pairsCount;
}
public int getNumberOfBits() {
return n;
}
public long getNumStatements() {
return numStatements;
}
}
ConsecutivePairsTest.java
public class ConsecutivePairsTest {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java ConsecutivePairsTest numberOfBits");
System.exit(1);
}
try {
int n = Integer.parseInt(args[0]);
ConsecutivePairs pairs = new ConsecutivePairs(n); //this is the call to measure
System.out.printf("for n = %d, there are %d matched bit pairs ",
n, pairs.getPairsCount());
System.out.printf("approximately %d statements were executed to calculate this
answer",
pairs.getNumStatements());
} catch (Exception nfe) {
System.out.println("number of bits must be a positive integer");
nfe.printStackTrace();
System.exit(1);
}
}
}
analysis.odt
Haseeb Nain
Computer Science 221
Mason Vail
FindSort:
Part 1 Section 1
Because this sort relies on finding a specific value at the within the array. And in doing so finds
multiple values at multiple points within the array it must be at least O(n). This is simply because
the amount of recursion is directly related to the size of the array.
Part 1 Section 2
Table 1 FindSort Data
FindSort
Input Average NumStatements
1000 500 500000
10000 5000 50000000
20000 10000 200000000
30000 15000 450000000
40000 20000 800000000
50000 25000 1250000000
Figure 1: FindSort Average
Figure 2: FindSort Statments
Part 1 Section 3
This outcome did not support my hypothesis, I believed that the array simply relied on the
length of the array, n, this is not the case. While the average was constant, the actual amount of
time the statements were run followed more closely to a O(n2).
Order Sort:
Part 2 Section 1
Because this sort relies on the value of a point in an array, and then compares the two arrays,
and then switches the position of the array based on its size in comparison, this sort will be
greater in magnitude than the previous FindSort. The order.java class seems to make the
comparison, so it must always run twice for each loop, the loop is the size of the array, so it will
repeat n times. When putting these together I arrive at a O(n2).
Part 2 Section 2
Table 2: OrderSort Data
OrderSort
Input NumStatements
1000 247753
10000 25256933
20000 1.00E+08
30000 2.24E+08
40000 3.98E+08
50000 6.23E+08
Figure 3: OrderSort Statements
Part 2 Section 3
After plotting the number of statements in relation to the number of inputs, I noticed that the
graph looked similar to the quadratic of the second power. This confirms my hypothesis of
O(n2).
BeiberSort:
Part 3 Section 1
BeiberSort is similar to Consecutive Sort, as it compares two values and then orders them from
lowest to greatest. Because it also follows though with two for loops, I believe this will also be
O(n2).
Part 3 Section 2
Table 3: BeiberSort Data
BeiberSort
Input Count
1000 499500
10000 49995000
20000 199990000
30000 449985000
40000 799980000
50000 1249975000
Figure 4: BeiberSort Statements
Part 3 Section 3
The information exracted from the amount of statements and the amount of inputs provides a
graph with a plot equivalent to a quadratic of power 2. This further confirms my hypothesis that
O(n2)
ConsecutiveSort:
Part 4 Section 1
Because the consecutive sort merges concepts from the previous sorting methods, I believe its
number of statements run must be larger then anything before. The consecutive sort will find
values, then compare the values and report values where two values are equivalent and
consecutive. The use of a while loop will also contribute to the amount of statements run,
because it directly relates to the size of “n”. In the end I believe this to be an exponential
increase, so O(2n).
Part 4 Section 2
Table 4: ConsecutiveSort Data
ConsecutiveSort
Input NumStatements
5 31
10 1023
15 32767
20 1048575
25 33554431
Figure 5: ConsecutiveSort Statements
Part 4 Section 3
The information provided by the input and the number of statements further confirms my
hypothesis. The slope was minimal at first by begins to ramp up significantly after 20. On my
excel sheet the data went negative for the value between 15 and 20, I believe this is simply an
error on the behalf of Excel.

More Related Content

Similar to OrderTest.javapublic class OrderTest {       Get an arra.pdf (20)

PDF
Microsoft word java
Ravi Purohit
 
PDF
GLA-01- Java- Big O and Lists Overview and Submission Requirements You.pdf
NicholasflqStewartl
 
PDF
LeetCode April Coding Challenge
Sunil Yadav
 
PDF
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
PDF
450 dsa (1).pdf
karansharma193921
 
PPTX
Building Java Programas
ssuser4df5ef
 
PPT
Chapter three data structure and algorithms qaybta quee
habdi203062
 
PDF
Programming in Java: Arrays
Martin Chapman
 
PPT
Algorithms with-java-advanced-1.0
BG Java EE Course
 
PPTX
Virtusa questions placement preparation guide
ThalaAjith33
 
PDF
Objectives In this lab you will review passing arrays to methods and.pdf
f3apparelsonline
 
PDF
Essential Problems Every Developer Should Know in Data Structures and Algorithms
KantubhukthaJanardha
 
PPTX
Arrays.pptx
Epsiba1
 
PPTX
Presentation1 computer shaan
walia Shaan
 
PDF
CS3381 OBJECT ORIENTED PROGRAMMINGLABS_1.pdf
deepak14367
 
PDF
LeetCode Solutions In Java .pdf
zupsezekno
 
PDF
04 sorting
martchasera92
 
PPT
ch07-arrays.ppt
Mahyuddin8
 
PDF
Refer to my progress on this assignment belowIn this problem you w.pdf
arishmarketing21
 
PPTX
First session _Cracking the coding interview.pptx
ZilvinasAleksa
 
Microsoft word java
Ravi Purohit
 
GLA-01- Java- Big O and Lists Overview and Submission Requirements You.pdf
NicholasflqStewartl
 
LeetCode April Coding Challenge
Sunil Yadav
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
450 dsa (1).pdf
karansharma193921
 
Building Java Programas
ssuser4df5ef
 
Chapter three data structure and algorithms qaybta quee
habdi203062
 
Programming in Java: Arrays
Martin Chapman
 
Algorithms with-java-advanced-1.0
BG Java EE Course
 
Virtusa questions placement preparation guide
ThalaAjith33
 
Objectives In this lab you will review passing arrays to methods and.pdf
f3apparelsonline
 
Essential Problems Every Developer Should Know in Data Structures and Algorithms
KantubhukthaJanardha
 
Arrays.pptx
Epsiba1
 
Presentation1 computer shaan
walia Shaan
 
CS3381 OBJECT ORIENTED PROGRAMMINGLABS_1.pdf
deepak14367
 
LeetCode Solutions In Java .pdf
zupsezekno
 
04 sorting
martchasera92
 
ch07-arrays.ppt
Mahyuddin8
 
Refer to my progress on this assignment belowIn this problem you w.pdf
arishmarketing21
 
First session _Cracking the coding interview.pptx
ZilvinasAleksa
 

More from akkhan101 (20)

PDF
1.Cexplanation; Cloud consumers that use cloud-based IT resources .pdf
akkhan101
 
PDF
1) WBC count is high and this level indicates that the person has le.pdf
akkhan101
 
PDF
What are the four steps of a process involving a heterogeneous catal.pdf
akkhan101
 
PDF
The given function is-Strictly increasing from 2 to infinityHen.pdf
akkhan101
 
PDF
In the span of several decades, the Kingdom Protista has been disass.pdf
akkhan101
 
PDF
Information privacy It refers to the collection of data and disse.pdf
akkhan101
 
PDF
H2SO4 --- 2H+ + SO42-1 mole of H2SO4 produces 2 moles of H+ ions.pdf
akkhan101
 
PDF
Gene editing of somatic cellsThere are grave concerns regarding th.pdf
akkhan101
 
PDF
Four parts of compare and contrastSolutionFour parts of compar.pdf
akkhan101
 
PDF
Each Restriction enzymes has a unique restriction site and therefore.pdf
akkhan101
 
PDF
correctSolutioncorrect.pdf
akkhan101
 
PDF
Code of main classpublic class LBmain {    public static void m.pdf
akkhan101
 
PDF
BibliographyHall, J. E. (2015). Guyton and Hall textbook of medic.pdf
akkhan101
 
PDF
synthesis .pdf
akkhan101
 
PDF
LiOH is a strong base so we assume it dissociates.pdf
akkhan101
 
PDF
With Sp3d hybridization, a seesaw or linear shape.pdf
akkhan101
 
PDF
Two-photon transition probability .pdf
akkhan101
 
PDF
this is because Nitrogen has a lone pair and and .pdf
akkhan101
 
PDF
There is no easy way to remember the ionization l.pdf
akkhan101
 
PDF
My opinion is to carry out in the complete absenc.pdf
akkhan101
 
1.Cexplanation; Cloud consumers that use cloud-based IT resources .pdf
akkhan101
 
1) WBC count is high and this level indicates that the person has le.pdf
akkhan101
 
What are the four steps of a process involving a heterogeneous catal.pdf
akkhan101
 
The given function is-Strictly increasing from 2 to infinityHen.pdf
akkhan101
 
In the span of several decades, the Kingdom Protista has been disass.pdf
akkhan101
 
Information privacy It refers to the collection of data and disse.pdf
akkhan101
 
H2SO4 --- 2H+ + SO42-1 mole of H2SO4 produces 2 moles of H+ ions.pdf
akkhan101
 
Gene editing of somatic cellsThere are grave concerns regarding th.pdf
akkhan101
 
Four parts of compare and contrastSolutionFour parts of compar.pdf
akkhan101
 
Each Restriction enzymes has a unique restriction site and therefore.pdf
akkhan101
 
correctSolutioncorrect.pdf
akkhan101
 
Code of main classpublic class LBmain {    public static void m.pdf
akkhan101
 
BibliographyHall, J. E. (2015). Guyton and Hall textbook of medic.pdf
akkhan101
 
synthesis .pdf
akkhan101
 
LiOH is a strong base so we assume it dissociates.pdf
akkhan101
 
With Sp3d hybridization, a seesaw or linear shape.pdf
akkhan101
 
Two-photon transition probability .pdf
akkhan101
 
this is because Nitrogen has a lone pair and and .pdf
akkhan101
 
There is no easy way to remember the ionization l.pdf
akkhan101
 
My opinion is to carry out in the complete absenc.pdf
akkhan101
 
Ad

Recently uploaded (20)

PPTX
Top 10 AI Tools, Like ChatGPT. You Must Learn In 2025
Digilearnings
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PPTX
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
PPTX
Applied-Statistics-1.pptx hardiba zalaaa
hardizala899
 
PPTX
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
PPTX
ENGLISH 8 WEEK 3 Q1 - Analyzing the linguistic, historical, andor biographica...
OliverOllet
 
PPTX
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Introduction to Probability(basic) .pptx
purohitanuj034
 
PDF
John Keats introduction and list of his important works
vatsalacpr
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PDF
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
PPTX
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
Top 10 AI Tools, Like ChatGPT. You Must Learn In 2025
Digilearnings
 
Virus sequence retrieval from NCBI database
yamunaK13
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
Applied-Statistics-1.pptx hardiba zalaaa
hardizala899
 
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
ENGLISH 8 WEEK 3 Q1 - Analyzing the linguistic, historical, andor biographica...
OliverOllet
 
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
Introduction to Probability(basic) .pptx
purohitanuj034
 
John Keats introduction and list of his important works
vatsalacpr
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
Ad

OrderTest.javapublic class OrderTest {       Get an arra.pdf

  • 1. OrderTest.java public class OrderTest { /** * Get an array of specified size and pass it to Order.order(). * Report the results. */ public static void main(String[] args) { if (args.length != 1) {//1 System.out.println("Usage: java OrderTest sizeOfArray " + "tor tjava OrderTest arrayFile"); System.exit(1); } // create or read the int[] int size = 0; int[] array = new int[0];//5 try { size = Integer.parseInt(args[0]); array = ArrayOfInts.randomizedArray(size); } catch (NumberFormatException nfe) {//8 try { array = ArrayOfInts.arrayFromFile(args[0]); size = array.length; } catch (Exception e) { System.err.println("unable to read array from " + args[0]); System.exit(1);//14 } } System.out.println("before:");//15 for (int i = 0; i < array.length; i++) {//2 n System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);//1 } int myNum = Order.order(array); //this is the call we want to measure
  • 2. System.out.println(" after:");//18 for (int i = 0; i < array.length; i++) {//2 n System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]); } System.out.println(myNum); } } ArrayOfInts.java import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.InputMismatchException; import java.util.Scanner; public class ArrayOfInts { /** * Returns an array of consecutive ints from 1 to size. */ public static int[] orderedArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = i+1; } return a; } /** * Returns a randomized array containing ints from 1 to size.
  • 3. */ public static int[] randomizedArray(int size) { ArrayList aL = new ArrayList(); for (int i = 0; i < size; i++) { aL.add(i+1); } Collections.shuffle(aL); int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = aL.get(i); } return a; } /** * Writes an int[] to a plain-text file with ints separated by spaces. * Useful for creating input files for repeatable tests. */ public static void arrayToFile(int[] array, String outfile) { try { FileWriter fw = new FileWriter(outfile); BufferedWriter bw = new BufferedWriter(fw); PrintWriter outFile = new PrintWriter(bw); for (int i : array) { outFile.print(i + " "); } outFile.close(); } catch (IOException e) { System.err.println("Could not write to " + outfile + " " + e); } } /** * Read ints from a file and return them in an int[] */ public static int[] arrayFromFile(String infile) throws FileNotFoundException,
  • 4. InputMismatchException { Scanner scan = new Scanner(new File(infile)); ArrayList aL = new ArrayList(); while (scan.hasNext()) { aL.add(scan.nextInt()); } scan.close(); int[] a = new int[aL.size()]; for (int i = 0; i < a.length; i++) { a[i] = aL.get(i); } return a; } } Order.java public class Order { /** * Take an int[] and reorganize it so they are in ascending order. */ public static int order(int[] array) { int myNum = 0; for (int next = 1; next < array.length; next++) {//2 //n myNum++; int val = array[next]; int index = next; while (index > 0 && val < array[index - 1]) {//3 array[index] = array[index - 1];//n index--; myNum++; } array[index] = val; } return myNum;
  • 5. } } BieberSortTest.java public class BieberSortTest { public static void main(String[] args){ if (args.length != 1) { System.out.println("Usage: java BieberSortTest numberOfBiebz"); System.exit(1); } try { int n = Integer.parseInt(args[0]); BieberSort bs = new BieberSort(n); bs.printBiebers(); System.out.println("---------"); bs.sort(); // this is the method to measure bs.printBiebers(); System.out.println(bs.getLoop1()+" <==Loop1"); System.out.println(bs.getLoop2()+" <==Loop"); } catch (NumberFormatException nfe) { System.out.println("number of Biebz must be a positive integer"); nfe.printStackTrace(); } } } BiberSort.java import java.util.Random; public class BieberSort { private Biebz[] theBiebz;
  • 6. int counterLoop1=0,counterLoop2=0; /** * Inner class for the BieberSort */ public class Biebz implements Comparable{ private int b; public Biebz(int b){ this.b = b; } public int compareTo(Biebz o) { return this.b - o.b; } public String toString() { return String.valueOf(this.b); } } /** * Construct a new BieberSort class with n fans */ public BieberSort(int n) { this.theBiebz = new Biebz[n]; Random rdm = new Random(System.currentTimeMillis()); for(int i = 0; i< n;i++){ theBiebz[i] = new Biebz(rdm.nextInt(n)); } } public int getLoop1(){ return counterLoop1; } public int getLoop2(){ return counterLoop2; } /** * Prints all the Biebers that we have ...
  • 7. */ public void printBiebers(){ for(Biebz bz:theBiebz){ System.out.println(bz); } } /** * Sorts a collection of Bieber objects */ public void sort(){ for(int i =0;ii;j--){ counterLoop2++; if(theBiebz[i].compareTo(theBiebz[j]) > 0 ){ swap(i,j); } } } } private void swap(int i, int j){ Biebz b =theBiebz[i]; theBiebz[i] = theBiebz[j]; theBiebz[j]=b; } } FindTest.java public class FindTest { /** * Get an array of specified size and find the indexes of all elements * in the array using Find.find(). */ public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: java FindTest sizeOfArray " + "tor tjava FindTest arrayFile");
  • 8. System.exit(1); } // create or read the int[] int size = 0; int counter = 0; int[] array = new int[0]; try { size = Integer.parseInt(args[0]); array = ArrayOfInts.randomizedArray(size); } catch (NumberFormatException nfe) { try { array = ArrayOfInts.arrayFromFile(args[0]); size = array.length; } catch (Exception e) { System.err.println("unable to read array from " + args[0]); System.exit(1); } } // find the index of every element double average=0; for (int i = 1; i <= array.length; i++) { //this is the method of interest, but you'll need to average //the number of statements needed to find each element for //meaningful results int index = Find.find(array, i); average = Find.getAverage(array); System.out.printf("%d found at index %d ", i, index); } System.out.println("The average is: "+average); System.out.println(size); } }
  • 9. Find.java public class Find { /** * Return index where value is found in array or -1 if not found. */ public static int find(int[] array, int value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return -1; } public static double getAverage(int[] myArray){ int sum=0; double average=0; for (int i = 0; i < myArray.length; i++) { sum=sum+myArray[i]; } average=sum/myArray.length; return average; } } ConsecutivePairs.java public class ConsecutivePairs { private int n; private long pairsCount; private long numStatements = 0; //looking for the dominant section as n gets large
  • 10. /** * Generates all combinations of numberOfBits and counts all matched bit pairs. */ public ConsecutivePairs(int numberOfBits) throws IllegalArgumentException { if (numberOfBits < 1) { throw new IllegalArgumentException("number of bits must be positive"); } n = numberOfBits; pairsCount = 0; int[] bit = new int[n]; for (int i = 0; i < bit.length; i++) { bit[i] = 0; } //generate all combinations of n "bits" by mimicking a binary counter while(positivesCount(bit) < n) { numStatements++; //are these the most important statements? //count "bits" that match their neighbor for(int i = 0; i < bit.length - 1; i++) { //numStatements++; //are these the most important statements? if(bit[i] == bit[i+1]) { pairsCount++; } } //add 1 int b = 0; while (b < bit.length && bit[b] == 1) { bit[b] = 0; b++;
  • 11. //numStatements++; //are these the most important statements? } if (b < bit.length) { bit[b] = 1; } } //still need to count last state where all bits are 1s //count "bits" that match their neighbor for(int i = 0; i < bit.length - 1; i++) { //numStatements++; //are these the most important statements? if(bit[i] == bit[i+1]) { pairsCount++; } } } private int positivesCount(int[] intsArray) { int positives = 0; for(int i = 0; i < intsArray.length; i++) { //numStatements++; //are these the most important statements? if(intsArray[i] > 0) { positives++; } } return positives; } public long getPairsCount() { return pairsCount; }
  • 12. public int getNumberOfBits() { return n; } public long getNumStatements() { return numStatements; } } ConsecutivePairsTest.java public class ConsecutivePairsTest { public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: java ConsecutivePairsTest numberOfBits"); System.exit(1); } try { int n = Integer.parseInt(args[0]); ConsecutivePairs pairs = new ConsecutivePairs(n); //this is the call to measure System.out.printf("for n = %d, there are %d matched bit pairs ", n, pairs.getPairsCount()); System.out.printf("approximately %d statements were executed to calculate this answer", pairs.getNumStatements()); } catch (Exception nfe) { System.out.println("number of bits must be a positive integer"); nfe.printStackTrace(); System.exit(1); } } } analysis.odt Haseeb Nain
  • 13. Computer Science 221 Mason Vail FindSort: Part 1 Section 1 Because this sort relies on finding a specific value at the within the array. And in doing so finds multiple values at multiple points within the array it must be at least O(n). This is simply because the amount of recursion is directly related to the size of the array. Part 1 Section 2 Table 1 FindSort Data FindSort Input Average NumStatements 1000 500 500000 10000 5000 50000000 20000 10000 200000000 30000 15000 450000000 40000 20000 800000000 50000 25000 1250000000 Figure 1: FindSort Average Figure 2: FindSort Statments Part 1 Section 3 This outcome did not support my hypothesis, I believed that the array simply relied on the length of the array, n, this is not the case. While the average was constant, the actual amount of time the statements were run followed more closely to a O(n2). Order Sort: Part 2 Section 1 Because this sort relies on the value of a point in an array, and then compares the two arrays, and then switches the position of the array based on its size in comparison, this sort will be greater in magnitude than the previous FindSort. The order.java class seems to make the comparison, so it must always run twice for each loop, the loop is the size of the array, so it will repeat n times. When putting these together I arrive at a O(n2). Part 2 Section 2 Table 2: OrderSort Data OrderSort Input NumStatements
  • 14. 1000 247753 10000 25256933 20000 1.00E+08 30000 2.24E+08 40000 3.98E+08 50000 6.23E+08 Figure 3: OrderSort Statements Part 2 Section 3 After plotting the number of statements in relation to the number of inputs, I noticed that the graph looked similar to the quadratic of the second power. This confirms my hypothesis of O(n2). BeiberSort: Part 3 Section 1 BeiberSort is similar to Consecutive Sort, as it compares two values and then orders them from lowest to greatest. Because it also follows though with two for loops, I believe this will also be O(n2). Part 3 Section 2 Table 3: BeiberSort Data BeiberSort Input Count 1000 499500 10000 49995000 20000 199990000 30000 449985000 40000 799980000 50000 1249975000 Figure 4: BeiberSort Statements Part 3 Section 3 The information exracted from the amount of statements and the amount of inputs provides a graph with a plot equivalent to a quadratic of power 2. This further confirms my hypothesis that O(n2) ConsecutiveSort: Part 4 Section 1 Because the consecutive sort merges concepts from the previous sorting methods, I believe its number of statements run must be larger then anything before. The consecutive sort will find
  • 15. values, then compare the values and report values where two values are equivalent and consecutive. The use of a while loop will also contribute to the amount of statements run, because it directly relates to the size of “n”. In the end I believe this to be an exponential increase, so O(2n). Part 4 Section 2 Table 4: ConsecutiveSort Data ConsecutiveSort Input NumStatements 5 31 10 1023 15 32767 20 1048575 25 33554431 Figure 5: ConsecutiveSort Statements Part 4 Section 3 The information provided by the input and the number of statements further confirms my hypothesis. The slope was minimal at first by begins to ramp up significantly after 20. On my excel sheet the data went negative for the value between 15 and 20, I believe this is simply an error on the behalf of Excel. Solution OrderTest.java public class OrderTest { /** * Get an array of specified size and pass it to Order.order(). * Report the results. */ public static void main(String[] args) { if (args.length != 1) {//1 System.out.println("Usage: java OrderTest sizeOfArray " + "tor tjava OrderTest arrayFile"); System.exit(1); }
  • 16. // create or read the int[] int size = 0; int[] array = new int[0];//5 try { size = Integer.parseInt(args[0]); array = ArrayOfInts.randomizedArray(size); } catch (NumberFormatException nfe) {//8 try { array = ArrayOfInts.arrayFromFile(args[0]); size = array.length; } catch (Exception e) { System.err.println("unable to read array from " + args[0]); System.exit(1);//14 } } System.out.println("before:");//15 for (int i = 0; i < array.length; i++) {//2 n System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]);//1 } int myNum = Order.order(array); //this is the call we want to measure System.out.println(" after:");//18 for (int i = 0; i < array.length; i++) {//2 n System.out.printf(((i+1) % 10 > 0) ? " %d" : " %d ", array[i]); } System.out.println(myNum); } } ArrayOfInts.java import java.io.BufferedWriter;
  • 17. import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.InputMismatchException; import java.util.Scanner; public class ArrayOfInts { /** * Returns an array of consecutive ints from 1 to size. */ public static int[] orderedArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = i+1; } return a; } /** * Returns a randomized array containing ints from 1 to size. */ public static int[] randomizedArray(int size) { ArrayList aL = new ArrayList(); for (int i = 0; i < size; i++) { aL.add(i+1); } Collections.shuffle(aL); int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = aL.get(i); } return a; }
  • 18. /** * Writes an int[] to a plain-text file with ints separated by spaces. * Useful for creating input files for repeatable tests. */ public static void arrayToFile(int[] array, String outfile) { try { FileWriter fw = new FileWriter(outfile); BufferedWriter bw = new BufferedWriter(fw); PrintWriter outFile = new PrintWriter(bw); for (int i : array) { outFile.print(i + " "); } outFile.close(); } catch (IOException e) { System.err.println("Could not write to " + outfile + " " + e); } } /** * Read ints from a file and return them in an int[] */ public static int[] arrayFromFile(String infile) throws FileNotFoundException, InputMismatchException { Scanner scan = new Scanner(new File(infile)); ArrayList aL = new ArrayList(); while (scan.hasNext()) { aL.add(scan.nextInt()); } scan.close(); int[] a = new int[aL.size()]; for (int i = 0; i < a.length; i++) { a[i] = aL.get(i); } return a; }
  • 19. } Order.java public class Order { /** * Take an int[] and reorganize it so they are in ascending order. */ public static int order(int[] array) { int myNum = 0; for (int next = 1; next < array.length; next++) {//2 //n myNum++; int val = array[next]; int index = next; while (index > 0 && val < array[index - 1]) {//3 array[index] = array[index - 1];//n index--; myNum++; } array[index] = val; } return myNum; } } BieberSortTest.java public class BieberSortTest { public static void main(String[] args){ if (args.length != 1) { System.out.println("Usage: java BieberSortTest numberOfBiebz"); System.exit(1); }
  • 20. try { int n = Integer.parseInt(args[0]); BieberSort bs = new BieberSort(n); bs.printBiebers(); System.out.println("---------"); bs.sort(); // this is the method to measure bs.printBiebers(); System.out.println(bs.getLoop1()+" <==Loop1"); System.out.println(bs.getLoop2()+" <==Loop"); } catch (NumberFormatException nfe) { System.out.println("number of Biebz must be a positive integer"); nfe.printStackTrace(); } } } BiberSort.java import java.util.Random; public class BieberSort { private Biebz[] theBiebz; int counterLoop1=0,counterLoop2=0; /** * Inner class for the BieberSort */ public class Biebz implements Comparable{ private int b; public Biebz(int b){ this.b = b; } public int compareTo(Biebz o) { return this.b - o.b; }
  • 21. public String toString() { return String.valueOf(this.b); } } /** * Construct a new BieberSort class with n fans */ public BieberSort(int n) { this.theBiebz = new Biebz[n]; Random rdm = new Random(System.currentTimeMillis()); for(int i = 0; i< n;i++){ theBiebz[i] = new Biebz(rdm.nextInt(n)); } } public int getLoop1(){ return counterLoop1; } public int getLoop2(){ return counterLoop2; } /** * Prints all the Biebers that we have ... */ public void printBiebers(){ for(Biebz bz:theBiebz){ System.out.println(bz); } } /** * Sorts a collection of Bieber objects */ public void sort(){ for(int i =0;ii;j--){ counterLoop2++; if(theBiebz[i].compareTo(theBiebz[j]) > 0 ){
  • 22. swap(i,j); } } } } private void swap(int i, int j){ Biebz b =theBiebz[i]; theBiebz[i] = theBiebz[j]; theBiebz[j]=b; } } FindTest.java public class FindTest { /** * Get an array of specified size and find the indexes of all elements * in the array using Find.find(). */ public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: java FindTest sizeOfArray " + "tor tjava FindTest arrayFile"); System.exit(1); } // create or read the int[] int size = 0; int counter = 0; int[] array = new int[0]; try { size = Integer.parseInt(args[0]); array = ArrayOfInts.randomizedArray(size); } catch (NumberFormatException nfe) { try {
  • 23. array = ArrayOfInts.arrayFromFile(args[0]); size = array.length; } catch (Exception e) { System.err.println("unable to read array from " + args[0]); System.exit(1); } } // find the index of every element double average=0; for (int i = 1; i <= array.length; i++) { //this is the method of interest, but you'll need to average //the number of statements needed to find each element for //meaningful results int index = Find.find(array, i); average = Find.getAverage(array); System.out.printf("%d found at index %d ", i, index); } System.out.println("The average is: "+average); System.out.println(size); } } Find.java public class Find { /** * Return index where value is found in array or -1 if not found. */ public static int find(int[] array, int value) { for (int i = 0; i < array.length; i++) { if (array[i] == value) { return i; } } return -1;
  • 24. } public static double getAverage(int[] myArray){ int sum=0; double average=0; for (int i = 0; i < myArray.length; i++) { sum=sum+myArray[i]; } average=sum/myArray.length; return average; } } ConsecutivePairs.java public class ConsecutivePairs { private int n; private long pairsCount; private long numStatements = 0; //looking for the dominant section as n gets large /** * Generates all combinations of numberOfBits and counts all matched bit pairs. */ public ConsecutivePairs(int numberOfBits) throws IllegalArgumentException { if (numberOfBits < 1) { throw new IllegalArgumentException("number of bits must be positive"); } n = numberOfBits; pairsCount = 0; int[] bit = new int[n]; for (int i = 0; i < bit.length; i++) { bit[i] = 0;
  • 25. } //generate all combinations of n "bits" by mimicking a binary counter while(positivesCount(bit) < n) { numStatements++; //are these the most important statements? //count "bits" that match their neighbor for(int i = 0; i < bit.length - 1; i++) { //numStatements++; //are these the most important statements? if(bit[i] == bit[i+1]) { pairsCount++; } } //add 1 int b = 0; while (b < bit.length && bit[b] == 1) { bit[b] = 0; b++; //numStatements++; //are these the most important statements? } if (b < bit.length) { bit[b] = 1; } } //still need to count last state where all bits are 1s //count "bits" that match their neighbor for(int i = 0; i < bit.length - 1; i++) { //numStatements++; //are these the most important statements?
  • 26. if(bit[i] == bit[i+1]) { pairsCount++; } } } private int positivesCount(int[] intsArray) { int positives = 0; for(int i = 0; i < intsArray.length; i++) { //numStatements++; //are these the most important statements? if(intsArray[i] > 0) { positives++; } } return positives; } public long getPairsCount() { return pairsCount; } public int getNumberOfBits() { return n; } public long getNumStatements() { return numStatements; } } ConsecutivePairsTest.java public class ConsecutivePairsTest { public static void main(String[] args) { if (args.length != 1) {
  • 27. System.out.println("Usage: java ConsecutivePairsTest numberOfBits"); System.exit(1); } try { int n = Integer.parseInt(args[0]); ConsecutivePairs pairs = new ConsecutivePairs(n); //this is the call to measure System.out.printf("for n = %d, there are %d matched bit pairs ", n, pairs.getPairsCount()); System.out.printf("approximately %d statements were executed to calculate this answer", pairs.getNumStatements()); } catch (Exception nfe) { System.out.println("number of bits must be a positive integer"); nfe.printStackTrace(); System.exit(1); } } } analysis.odt Haseeb Nain Computer Science 221 Mason Vail FindSort: Part 1 Section 1 Because this sort relies on finding a specific value at the within the array. And in doing so finds multiple values at multiple points within the array it must be at least O(n). This is simply because the amount of recursion is directly related to the size of the array. Part 1 Section 2 Table 1 FindSort Data FindSort Input Average NumStatements 1000 500 500000
  • 28. 10000 5000 50000000 20000 10000 200000000 30000 15000 450000000 40000 20000 800000000 50000 25000 1250000000 Figure 1: FindSort Average Figure 2: FindSort Statments Part 1 Section 3 This outcome did not support my hypothesis, I believed that the array simply relied on the length of the array, n, this is not the case. While the average was constant, the actual amount of time the statements were run followed more closely to a O(n2). Order Sort: Part 2 Section 1 Because this sort relies on the value of a point in an array, and then compares the two arrays, and then switches the position of the array based on its size in comparison, this sort will be greater in magnitude than the previous FindSort. The order.java class seems to make the comparison, so it must always run twice for each loop, the loop is the size of the array, so it will repeat n times. When putting these together I arrive at a O(n2). Part 2 Section 2 Table 2: OrderSort Data OrderSort Input NumStatements 1000 247753 10000 25256933 20000 1.00E+08 30000 2.24E+08 40000 3.98E+08 50000 6.23E+08 Figure 3: OrderSort Statements Part 2 Section 3 After plotting the number of statements in relation to the number of inputs, I noticed that the graph looked similar to the quadratic of the second power. This confirms my hypothesis of O(n2). BeiberSort: Part 3 Section 1
  • 29. BeiberSort is similar to Consecutive Sort, as it compares two values and then orders them from lowest to greatest. Because it also follows though with two for loops, I believe this will also be O(n2). Part 3 Section 2 Table 3: BeiberSort Data BeiberSort Input Count 1000 499500 10000 49995000 20000 199990000 30000 449985000 40000 799980000 50000 1249975000 Figure 4: BeiberSort Statements Part 3 Section 3 The information exracted from the amount of statements and the amount of inputs provides a graph with a plot equivalent to a quadratic of power 2. This further confirms my hypothesis that O(n2) ConsecutiveSort: Part 4 Section 1 Because the consecutive sort merges concepts from the previous sorting methods, I believe its number of statements run must be larger then anything before. The consecutive sort will find values, then compare the values and report values where two values are equivalent and consecutive. The use of a while loop will also contribute to the amount of statements run, because it directly relates to the size of “n”. In the end I believe this to be an exponential increase, so O(2n). Part 4 Section 2 Table 4: ConsecutiveSort Data ConsecutiveSort Input NumStatements 5 31 10 1023 15 32767 20 1048575
  • 30. 25 33554431 Figure 5: ConsecutiveSort Statements Part 4 Section 3 The information provided by the input and the number of statements further confirms my hypothesis. The slope was minimal at first by begins to ramp up significantly after 20. On my excel sheet the data went negative for the value between 15 and 20, I believe this is simply an error on the behalf of Excel.