- 1. package org.idcn.jse;
- 2.
- 3. public class SortAll {
- 4.
- 5. /**
- 6. * 冒泡排序,选择排序,插入排序,希尔(Shell)排序 Java的实现
- 9. */
- 10. public static void main(String[] args) {
- 11. int[] i = { 1, 5, 6, 12, 4, 9, 3, 23, 39, 403, 596, 87 };
- 12. System.out.println("----冒泡排序的结果:");
- 13. maoPao(i);
- 14. System.out.println();
- 15. System.out.println("----选择排序的结果:");
- 16. xuanZe(i);
- 17. System.out.println();
- 18. System.out.println("----插入排序的结果:");
- 19. chaRu(i);
- 20. System.out.println();
- 21. System.out.println("----希尔(Shell)排序的结果:");
- 22. shell(i);
- 23. }
- 24.
- 25. // 冒泡排序
- 26. public static void maoPao(int[] x) {
- 27. for (int i = 0; i < x.length; i++) {
- 28. for (int j = i + 1; j < x.length; j++) {
- 29. if (x[i] > x[j]) {
- 30. int temp = x[i];
- 31. x[i] = x[j];
- 32. x[j] = temp;
- 33. }
- 34. }
- 35. }
- 36. for (int i : x) {
- 37. System.out.print(i + " ");
- 38. }
- 39. }
- 40.
- 41. // 选择排序
- 42. public static void xuanZe(int[] x) {
- 43. for (int i = 0; i < x.length; i++) {
- 44. int lowerIndex = i;
- 45. // 找出最小的一个索引
- 46. for (int j = i + 1; j < x.length; j++) {
- 47. if (x[j] < x[lowerIndex]) {
- 48. lowerIndex = j;
- 49. }
- 50. }
- 51. // 交换
- 52. int temp = x[i];
- 53. x[i] = x[lowerIndex];
- 54. x[lowerIndex] = temp;
- 55. }
- 56. for (int i : x) {
- 57. System.out.print(i + " ");
- 58. }
- 59. }
- 60.
- 61. // 插入排序
- 62. public static void chaRu(int[] x) {
- 63. for (int i = 1; i < x.length; i++) {// i从一开始,因为第一个数已经是排好序的啦
- 64. for (int j = i; j > 0; j--) {
- 65. if (x[j] < x[j - 1]) {
- 66. int temp = x[j];
- 67. x[j] = x[j - 1];
- 68. x[j - 1] = temp;
- 69. }
- 70. }
- 71. }
- 72. for (int i : x) {
- 73. System.out.print(i + " ");
- 74. }
- 75. }
- 76.
- 77. // 希尔排序
- 78. public static void shell(int[] x) {
- 79. // 分组
- 80. for (int increment = x.length / 2; increment > 0; increment /= 2) {
- 81. // 每个组内排序
- 82. for (int i = increment; i < x.length; i++) {
- 83. int temp = x[i];
- 84. int j = 0;
- 85. for (j = i; j >= increment; j -= increment) {
- 86. if (temp < x[j - increment]) {
- 87. x[j] = x[j - increment];
- 88. } else {
- 89. break;
- 90. }
- 91. }
- 92. x[j] = temp;
- 93. }
- 94. }
- 95.
- 96. for (int i : x) {
- 97. System.out.print(i + " ");
- 98. }
- 99. }
- 100. }
数组排序总结(冒泡,选择,插入,希尔)
最新推荐文章于 2021-02-12 19:28:29 发布