Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SortingStart {
- static void say(String msg){ //print to screen function
- System.out.println(msg);
- }
- static void sayArr(double[] a ){ //function prints array to screen
- //for loop
- for(int i = 0; i < a.length; i++){
- //say each element
- say(""+a[i]);
- }
- }
- static double[] makeData(int size) {
- double[] myData = new double[size];
- for(int i = 0 ; i < myData.length; i++) {
- myData[i] = Math.random()*10000000.0;
- }
- return myData;
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- double[] data = new double[] {552.1, -5421, 15.1, 4, -3.14};
- boolean sorted = false;
- data = makeData(10000);
- int counter = 0;
- sayArr(data);
- say("**************");
- int end = data.length -1;
- //while array not sorted
- while(!sorted) {
- double temp = 0;
- sorted = true;//assume its been sorted
- //use a for loop
- for(int i = 0 ; i < end ; i++) {
- //compare the i'th element to the i + 1
- if ( data[i] > data[i+1]) {
- //if i > i + 1 swap them
- temp = data[i];//need to prevent copying the i+1 element
- data[i] = data[i+1];
- data[i+1] = temp;
- sorted = false;
- counter += 4;//for counting operations
- }
- counter++;
- }//end for
- end --;
- }//end while
- sayArr(data);
- say("***************");
- say("it took "+ counter + " operations to sort the array");
- }//end main function
- }
Add Comment
Please, Sign In to add comment