Java 1 - Arrays


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import java.util.Arrays;
  2.  
  3. public class A {
  4. public void bubblesort(double[] x) {
  5. for (int i = 0; i < x.length; i++) {
  6. for (int j = x.length - 1; j > 0; j--) {
  7. if (x[j - 1] > x[j]) {
  8. double tmp = x[j - 1];
  9. x[j - 1] = x[j];
  10. x[j] = tmp;
  11. }
  12. }
  13. }
  14. }
  15.  
  16. public void decreasingInsertionSort(double[] x) {
  17. for (int i = 1; i < x.length; i++) {
  18. double max = x[i];
  19. int j = i;
  20. while (j > 0 && x[j - 1] < max) { // change x[j - 1] > max to x[j - 1] < max
  21. x[j] = x[j - 1];
  22. j--;
  23. }
  24. x[j] = max;
  25. }
  26. }
  27.  
  28. public void employees() {
  29. int[][] employees = {{0, 2, 4, 3, 4, 5, 8, 8},
  30. {1, 7, 3, 4, 3, 3, 4, 4},
  31. {2, 3, 3, 4, 3, 3, 2, 2},
  32. {3, 9, 3, 4, 7, 3, 4, 1},
  33. {4, 3, 5, 4, 3, 6, 3, 8},
  34. {5, 3, 4, 4, 6, 3, 4, 4},
  35. {6, 3, 7, 4, 8, 3, 8, 4},
  36. {7, 6, 3, 5, 9, 2, 7, 9}};
  37. int[] sum = new int[8];
  38. for (int i = 0; i < employees.length; i++) {
  39. int no = employees[i][0];
  40. for (int j = 1; j < employees[i].length; j++) {
  41. sum[no] += employees[i][j];
  42. }
  43. }
  44. System.out.println(printEmployees(employees, sum));
  45. for (int i = 0; i < employees.length; i++) {
  46. for (int j = employees.length - 1; j > 0; j--) {
  47. if (sum[employees[j - 1][0]] < sum[employees[j][0]]) {
  48. int[] tmp = employees[j - 1];
  49. employees[j - 1] = employees[j];
  50. employees[j] = tmp;
  51. }
  52. }
  53. }
  54. System.out.println(printEmployees(employees, sum));
  55. }
  56.  
  57. public String printEmployees(int[][] employees, int[] sum) {
  58. String str = "\n \tSu M T W H F Sa Sum\n\n";
  59. for (int i = 0; i < employees.length; i++) {
  60. str += "Employee " + employees[i][0] + "\t";
  61. for (int j = 1; j < employees[i].length; j++) {
  62. str += employees[i][j] + " ";
  63. }
  64. str += sum[employees[i][0]] + "\n";
  65. }
  66. return str;
  67. }
  68.  
  69. public static void main(String []args) {
  70. // 6.18
  71. A a = new A();
  72. double[] x = {6.0, 4.4, 1.9, 2.9, 3.4, 2.9, 3.5};
  73. System.out.println(Arrays.toString(x));
  74. a.bubblesort(x);
  75. System.out.println(Arrays.toString(x));
  76. // 6.19
  77. double[] y = {6.0, 4.4, 1.9, 2.9, 3.4, 2.9, 3.5};
  78. System.out.println(Arrays.toString(y));
  79. a.decreasingInsertionSort(y);
  80. System.out.println(Arrays.toString(y));
  81. // 6.23
  82. a.employees();
  83. }
  84. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.