冒泡排序

冒泡排序.gif

  1. private static void bubbleSort(int[] arr) {
  2. for (int i = 0; i < arr.length; i++) {
  3. for (int j = i; j < arr.length - i - 1; j++) {
  4. if (arr[j] < arr[j + 1]) {
  5. int temp = arr[j + 1];
  6. arr[j + 1] = arr[j];
  7. arr[j] = temp;
  8. }
  9. }
  10. }
  11. }

选择排序

选择排序.gif

  1. public static void selectionSort(int[] arr) {
  2. int temp, min = 0;
  3. for (int i = 0; i < arr.length - 1; i++) {
  4. min = i;
  5. // 循环查找最小值
  6. for (int j = i + 1; j < arr.length; j++) {
  7. if (arr[min] > arr[j]) {
  8. min = j;
  9. }
  10. }
  11. if (min != i) {
  12. temp = arr[i];
  13. arr[i] = arr[min];
  14. arr[min] = temp;
  15. }
  16. }
  17. }

插入排序

插入排序.png

  1. public static void insertionSort(int[] arr){
  2. for (int i=1; i<arr.length; ++i){
  3. int value = arr[i];
  4. int position=i;
  5. while (position>0 && arr[position-1]>value){
  6. arr[position] = arr[position-1];
  7. position--;
  8. }
  9. arr[position] = value;
  10. }//loop i
  11. }

归并排序

归并排序.gif

  1. public static void mergeSort(int[] arr, int left, int right, int[] temp) {
  2. if (left < right) {
  3. //中间索引
  4. int mid = (left + right) / 2;
  5. //向左递归进行分解
  6. //0 - mid 即是0 - 3 {8,4,5,7}
  7. mergeSort(arr, left, mid, temp);
  8. //向右递归进行分解
  9. //mid+1 - midright 即是4 - 7 {1,3,6,2}
  10. mergeSort(arr, mid + 1, right, temp);
  11. //进行合并
  12. merge(arr, left, mid, right, temp);
  13. }
  14. }
  15. public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
  16. int i = left;
  17. int j = mid + 1;
  18. int k = 0;
  19. while (i <= mid && j <= right) {
  20. temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
  21. }
  22. while (i <= mid) {
  23. temp[k++] = arr[i++];
  24. }
  25. while (j <= right) {
  26. temp[k++] = arr[j++];
  27. }
  28. //把数据复制回原数组
  29. for (i = 0; i < k; ++i) {
  30. arr[left + i] = temp[i];
  31. }
  32. }