Drawing the curtains open, the night sky at dawn is crystal clear. Pale moonlight penetrates through thin clouds, spilling over the silent earth.Blurred moonlight filters through layers of misty fog, scattering mottled, illusory rays of light.
A breeze brushes my face, carrying the aroma of foliage. In the far distance, the on-and-off chorus of insects resonates in the empty valley, infusing vitality into the tranquil night. This long, soothing insect choir is like a natural lullaby, revitalizing the spirit.
The crisp air is tinged with the scent of grass. The luminous moon aloft, the gentle breeze, and the persistent insects' crisp chirping compose a serene, alluring scene that refreshes the mind and brings peaceful tranquility.
function sortArrays(arrays) {
// 按第一个元素排序
arrays.sort((a, b) => a[0] - b[0]);
let sorted = false;
while(!sorted) {
sorted = true;
for(let i = 0; i < arrays.length - 1; i++) {
// 如果相邻两个数组的第一个元素相同
if(arrays[i][0] === arrays[i+1][0]) {
// 就按第二个元素排序
if(arrays[i][1] > arrays[i+1][1]) {
let temp = arrays[i];
arrays[i] = arrays[i+1];
arrays[i+1] = temp;
sorted = false;
}
}
}
}
return arrays;
}
// 测试
let arrays = [[1, 4], [1, 3], [1, 5], [2, 1]];
console.log(sortArrays(arrays)); // [[1, 3], [1, 4], [1, 5], [2, 1]]
主要思路是:
首先按第一个元素排序
检查相邻两个数组的第一个元素是否相同,如果相同则按第二个元素排序
不断重复此过程,直到排序完成这个算法同样适用于任意多维数组的排序。
Sort2:
def sort_arrays(arrays):
# 将数组按照第一个元素进行排序
arrays.sort(key=lambda x: x[0])
# 检查是否需要继续按第二个元素排序
need_sort = True
while need_sort:
need_sort = False
for i in range(len(arrays) - 1):
if arrays[i][0] == arrays[i+1][0]:
if arrays[i][1] > arrays[i+1][1]:
arrays[i], arrays[i+1] = arrays[i+1], arrays[i]
need_sort = True
# 然后按照第三个元素排序
if need_sort:
arrays.sort(key=lambda x: x[1])
编程学习之基础:排序算法01
三种常见的排序算法在Python中的实现:
(lenster的编辑器怎么缩进行,没有搞清楚)
冒泡排序
def bubble_sort(nums): for i in range(len(nums)-1): for j in range(len(nums)-i-1): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j]
选择排序
def selection_sort(nums): for i in range(len(nums)-1): min_idx = i for j in range(i+1, len(nums)): if nums[j] < nums[min_idx]: min_idx = j nums[i], nums[min_idx] = nums[min_idx], nums[i]
快速排序
def quick_sort(nums): if len(nums) <= 1: return nums pivot = nums[len(nums) // 2] left = [x for x in nums if x < pivot] middle = [x for x in nums if x == pivot] right = [x for x in nums if x > pivot] return quick_sort(left) + middle + quick_sort(right)
示例
nums = [5, 3, 1, 4, 2] bubble_sort(nums) print(nums) # [1, 2, 3, 4, 5]nums = [5, 3, 1, 4, 2] selection_sort(nums) print(nums) # [1, 2, 3, 4, 5] nums = [5, 3, 1, 4, 2] quick_sort(nums) print(nums) # [1, 2, 3, 4, 5]
桃树就是桃树
从来不是,
也不会是别的树
一定会经历风雨,
只会结出桃子
这便是桃树的本性
宇宙给桃树,
也给你我安排
从来都一视同仁着
找到内置在生命中的本性
放弃其他徒劳的想法
知道自己是谁的那一刻
也就结出桃子