Guest User

Untitled

a guest
Oct 15th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. public class SortingStart {
  2.  
  3. static void say(String msg){ //print to screen function
  4.  
  5. System.out.println(msg);
  6. }
  7.  
  8. static void sayArr(double[] a ){ //function prints array to screen
  9. //for loop
  10. for(int i = 0; i < a.length; i++){
  11.  
  12. //say each element
  13. say(""+a[i]);
  14. }
  15. }
  16.  
  17.  
  18. static double[] makeData(int size) {
  19. double[] myData = new double[size];
  20. for(int i = 0 ; i < myData.length; i++) {
  21. myData[i] = Math.random()*10000000.0;
  22. }
  23.  
  24.  
  25. return myData;
  26. }
  27.  
  28.  
  29. public static void main(String[] args) {
  30. // TODO Auto-generated method stub
  31.  
  32.  
  33. double[] data = new double[] {552.1, -5421, 15.1, 4, -3.14};
  34. boolean sorted = false;
  35. data = makeData(10000);
  36. int counter = 0;
  37. sayArr(data);
  38. say("**************");
  39. int end = data.length -1;
  40.  
  41. //while array not sorted
  42.  
  43.  
  44. while(!sorted) {
  45.  
  46. double temp = 0;
  47. sorted = true;//assume its been sorted
  48.  
  49.  
  50. //use a for loop
  51. for(int i = 0 ; i < end ; i++) {
  52.  
  53. //compare the i'th element to the i + 1
  54. if ( data[i] > data[i+1]) {
  55. //if i > i + 1 swap them
  56. temp = data[i];//need to prevent copying the i+1 element
  57. data[i] = data[i+1];
  58. data[i+1] = temp;
  59. sorted = false;
  60. counter += 4;//for counting operations
  61. }
  62. counter++;
  63.  
  64. }//end for
  65. end --;
  66. }//end while
  67.  
  68. sayArr(data);
  69. say("***************");
  70. say("it took "+ counter + " operations to sort the array");
  71. }//end main function
  72. }
Add Comment
Please, Sign In to add comment