专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java冒泡排序(Java冒泡排序的简单例子)

temp10 2024-09-25 21:14:15 java教程 9 ℃ 0 评论
  1. package sort;
  2. import static sort.SortUtils.*;
  3. /**
  4. * @see SortAlgorithm
  5. */
  6. class BubbleSort implements SortAlgorithm {
  7. /**
  8. * This method implements the Generic Bubble Sort
  9. *
  10. * @param array The array to be sorted
  11. * Sorts the array in increasing order
  12. **/
  13. @Override
  14. public <T extends Comparable<T>> T[] sort(T array[]) {
  15. int last = array.length;
  16. //Sorting
  17. boolean swap;
  18. do {
  19. swap = false;
  20. for (int count = 0; count < last-1; count++) {
  21. if (less(array[count], array[count + 1])) {
  22. swap = swap(array, count, count + 1);
  23. }
  24. }
  25. last--;
  26. } while (swap);
  27. return array;
  28. }
  29. // Driver Program
  30. public static void main(String[] args) {
  31. // Integer Input
  32. Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
  33. BubbleSort bubbleSort = new BubbleSort();
  34. bubbleSort.sort(integers);
  35. // Output => 231, 78, 54, 23, 12, 9, 6, 4, 1
  36. print(integers);
  37. // String Input
  38. String[] strings = {"c", "a", "e", "b","d"};
  39. //Output => e, d, c, b, a
  40. print(bubbleSort.sort(strings));
  41. }
  42. }

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表