platojobs / SFLOG

Excerpted reading notes, is to read with their own study, work, research issues related to the sentences, paragraphs and so on according to the original text accurately transcription down. After extracting the original text, the source shall be indicated, including the title, author, publisher, date of publication, page number, etc., so as to facilitate quotation and verification. Excerpts should be selected, with usefulness as the standard for excerpts.
MIT License
5 stars 1 forks source link

Flutter的冒泡排序和快速排序 #338

Open platojobs opened 4 months ago

platojobs commented 4 months ago

// 冒泡排序 in Flutter
List<int> bubbleSort(List<int> arr) {
  int n = arr.length;
  for (int i = 0; i < n - 1; i++) {
    for (int j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  return arr;
}

// 快速排序 in Flutter
List<int> quickSort(List<int> arr) {
  if (arr.length <= 1) return arr;
  int pivot = arr[arr.length ~/ 2];
  List<int> left = [];
  List<int> right = [];
  for (int i = 0; i < arr.length; i++) {
    if (arr[i] < pivot) {
      left.add(arr[i]);
    } else if (arr[i] > pivot) {
      right.add(arr[i]);
    }
  }
  return [...quickSort(left), pivot, ...quickSort(right)];
}