文章

排序

2020.10.7 ・ 共 290 字,您可能需要 1 分钟阅读

Tags: 代码

public class P {
  public static void selectionSort(int[] arr) {
    for (int i = 0; i < arr.length - 1; ++i) {
      int temp = arr[i];
      int flag = i;
      for (int j = i + 1; j < arr.length; ++j) {
        if (arr[j] < temp) {
          temp = arr[j];
          flag = j;
        }
      }
      if (i != flag) {
        arr[flag] = arr[i];
        arr[i] = temp;
      }
    }
  }

  public static void main(String[] args) {
    int[] arr = {2, 5, 7, 2, 1};
    P.selectionSort(arr);
    for (int a : arr) {
      System.out.println(a);
    }
  }
}
public class P {
  public static void insertSort(int[] arr) {
    int temp;
    int h;
    for (int i = 1; i < arr.length; ++i) {
      temp = arr[i];
      if (arr[i] < arr[i - 1]) {
        for (h = i - 1; h >= 0 && temp < arr[h]; --h) {
          arr[h + 1] = arr[h];
        }
        arr[h + 1] = temp;
      }
    }
  }

  public static void main(String[] args) {
    int[] arr = {2, 5, 7, 2, 1};
    P.insertSort(arr);
    for (int a : arr) {
      System.out.println(a);
    }
  }
}
import java.util.Arrays;

public class P {
  public static void main(String[] args) {
    int[] arr = {1, 2, 3, 5, 1, 2};
    shellSort(arr);
    System.out.println(Arrays.toString(arr));
  }

  public static void shellSort(int[] arr) {
    int temp;
    for (int gap = arr.length / 2; gap >= 1; gap /= 2) {
      for (int i = gap; i < arr.length; ++i) {
        for (int j = i - gap; j >= 0; j -= gap) {
          if (arr[j] > arr[j + gap]) {
            temp = arr[j + gap];
            arr[j + gap] = arr[j];
            arr[j] = temp;
          }
        }
      }
    }
  }
}