SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
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.

Más contenido relacionado

Similar a OrderTest.javapublic class OrderTest {       Get an arra.pdf

Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
ICADCMLTPC
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
ravikapoorindia
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
fantasiatheoutofthef
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
kostikjaylonshaewe47
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
adityaraj7711
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
JAVA - Design a data structure IntSet that can hold a set of integers-.docx
JAVA - Design a data structure IntSet that can hold a set of integers-.docxJAVA - Design a data structure IntSet that can hold a set of integers-.docx
JAVA - Design a data structure IntSet that can hold a set of integers-.docx
olsenlinnea427
 
Java programs
Java programsJava programs
Java programs
jojeph
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Sunil Kumar Gunasekaran
 

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

Inheritance
InheritanceInheritance
Inheritance
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lab4
Lab4Lab4
Lab4
 
Creating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docxCreating Interface- Practice Program 6.docx
Creating Interface- Practice Program 6.docx
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
JAVA - Design a data structure IntSet that can hold a set of integers-.docx
JAVA - Design a data structure IntSet that can hold a set of integers-.docxJAVA - Design a data structure IntSet that can hold a set of integers-.docx
JAVA - Design a data structure IntSet that can hold a set of integers-.docx
 
Java generics
Java genericsJava generics
Java generics
 
Java programs
Java programsJava programs
Java programs
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
 
PathOfMostResistance
PathOfMostResistancePathOfMostResistance
PathOfMostResistance
 

Más de akkhan101

1.Cexplanation; Cloud consumers that use cloud-based IT resources .pdf
1.Cexplanation; Cloud consumers that use cloud-based IT resources .pdf1.Cexplanation; Cloud consumers that use cloud-based IT resources .pdf
1.Cexplanation; Cloud consumers that use cloud-based IT resources .pdf
akkhan101
 
What are the four steps of a process involving a heterogeneous catal.pdf
What are the four steps of a process involving a heterogeneous catal.pdfWhat are the four steps of a process involving a heterogeneous catal.pdf
What are the four steps of a process involving a heterogeneous catal.pdf
akkhan101
 
In the span of several decades, the Kingdom Protista has been disass.pdf
In the span of several decades, the Kingdom Protista has been disass.pdfIn the span of several decades, the Kingdom Protista has been disass.pdf
In the span of several decades, the Kingdom Protista has been disass.pdf
akkhan101
 
Gene editing of somatic cellsThere are grave concerns regarding th.pdf
Gene editing of somatic cellsThere are grave concerns regarding th.pdfGene editing of somatic cellsThere are grave concerns regarding th.pdf
Gene editing of somatic cellsThere are grave concerns regarding th.pdf
akkhan101
 
Code of main classpublic class LBmain {    public static void m.pdf
Code of main classpublic class LBmain {    public static void m.pdfCode of main classpublic class LBmain {    public static void m.pdf
Code of main classpublic class LBmain {    public static void m.pdf
akkhan101
 
BibliographyHall, J. E. (2015). Guyton and Hall textbook of medic.pdf
BibliographyHall, J. E. (2015). Guyton and Hall textbook of medic.pdfBibliographyHall, J. E. (2015). Guyton and Hall textbook of medic.pdf
BibliographyHall, J. E. (2015). Guyton and Hall textbook of medic.pdf
akkhan101
 

Más de akkhan101 (20)

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

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

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.