feat: complete dart code for chapter_searching and chapter_sorting (#526)

pull/543/head
liuyuxin 1 year ago committed by GitHub
parent 86209e0a7b
commit 53e18bc6d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,50 @@
/**
* File: binary_search_edge.dart
* Created Time: 2023-06-01
* Author: liuyuxin (gvenusleo@gmail.com)
*/
/* 二分查找最左一个元素 */
int binarySearchLeftEdge(List<int> nums, int target) {
int i = 0, j = nums.length - 1; // [0, n-1]
while (i <= j) {
int m = i + (j - i) ~/ 2; // m
if (nums[m] < target)
i = m + 1; // target [m+1, j]
else if (nums[m] > target)
j = m - 1; // target [i, m-1]
else
j = m - 1; // target [i, m-1]
}
if (i == nums.length || nums[i] != target) return -1; // -1
return i;
}
/* 二分查找最右一个元素 */
int binarySearchRightEdge(List<int> nums, int target) {
int i = 0, j = nums.length - 1; // [0, n-1]
while (i <= j) {
int m = i + (j - i) ~/ 2; // m
if (nums[m] < target)
i = m + 1; // target [m+1, j]
else if (nums[m] > target)
j = m - 1; // target [i, m-1]
else
i = m + 1; // target [m+1, j]
}
if (j < 0 || nums[j] != target) return -1; // -1
return j;
}
/* Driver Code */
void main() {
int target = 6;
List<int> nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
//
int indexLeft = binarySearchLeftEdge(nums, target);
print("数组中最左一个元素 6 的索引 = $indexLeft");
//
int indexRight = binarySearchRightEdge(nums, target);
print("数组中最右一个元素 6 的索引 = $indexRight");
}

@ -0,0 +1,49 @@
/**
* File: heap_sort.dart
* Created Time: 2023-06-01
* Author: liuyuxin (gvenusleo@gmail.com)
*/
/* 堆的长度为 n ,从节点 i 开始,从顶至底堆化 */
void siftDown(List<int> nums, int n, int i) {
while (true) {
// i, l, r ma
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
if (l < n && nums[l] > nums[ma]) ma = l;
if (r < n && nums[r] > nums[ma]) ma = r;
// i l, r
if (ma == i) break;
//
int temp = nums[i];
nums[i] = nums[ma];
nums[ma] = temp;
//
i = ma;
}
}
/* 堆排序 */
void heapSort(List<int> nums) {
//
for (int i = nums.length ~/ 2 - 1; i >= 0; i--) {
siftDown(nums, nums.length, i);
}
// n-1
for (int i = nums.length - 1; i > 0; i--) {
//
int tmp = nums[0];
nums[0] = nums[i];
nums[i] = tmp;
//
siftDown(nums, i, 0);
}
}
/* Driver Code */
void main() {
List<int> nums = [4, 1, 3, 1, 5, 2];
heapSort(nums);
print("堆排序完成后 nums = $nums");
}

@ -0,0 +1,29 @@
/**
* File: selection_sort.dart
* Created Time: 2023-06-01
* Author: liuyuxin (gvenusleo@gmail.com)
*/
/* 选择排序 */
void selectionSort(List<int> nums) {
int n = nums.length;
// [i, n-1]
for (int i = 0; i < n - 1; i++) {
//
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k]) k = j; //
}
//
int temp = nums[i];
nums[i] = nums[k];
nums[k] = temp;
}
}
/* Driver Code */
void main() {
List<int> nums = [4, 1, 3, 1, 5, 2];
selectionSort(nums);
print("选择排序完成后 nums = $nums");
}
Loading…
Cancel
Save