Replies: 13 comments 4 replies
-
C++ 里面有 |
Beta Was this translation helpful? Give feedback.
-
里面的for循环迭代条件去掉等于,数组下标越界异常 |
Beta Was this translation helpful? Give feedback.
-
假如支持 C++17, 可以写 |
Beta Was this translation helpful? Give feedback.
-
只是因为swap操作就说明这是不稳定的吗?为什么? |
Beta Was this translation helpful? Give feedback.
-
因为可能导致相同数字之间的相对顺序发生变化,所以是不稳定的排序,而冒泡排序不会导致 |
Beta Was this translation helpful? Give feedback.
-
python版本的代码那里第一个for,应该是for i in range(n);第二个for,应该是for j in range(i+1,n)才对吧?或者说代码第0位是保留的,从1开始索引? |
Beta Was this translation helpful? Give feedback.
-
为了区别是第i个大小的元素吧 是从1开始索引的 |
Beta Was this translation helpful? Give feedback.
-
python 版本 代码有问题, 执行出错 可尝试我这个, 可正常运行
|
Beta Was this translation helpful? Give feedback.
-
C++错误:runtime error!
} |
Beta Was this translation helpful? Give feedback.
-
Python代碼錯到離譜了 應該是:
|
Beta Was this translation helpful? Give feedback.
-
双向选择排序:每次选出一个最大值和一个最小值 class Solution {
// 选择排序优化:双向选择排序
public int[] sortArray(int[] nums) {
for(int i = 0; i < nums.length / 2; i++ ){
int minIndex = i, maxIndex = i;
for(int j = i; j < nums.length - i; j++){
if(nums[j] > nums[maxIndex]) maxIndex = j;
if(nums[j] < nums[minIndex]) minIndex = j;
}
// 最小值移动到left
int temp = nums[i];
nums[i] = nums[minIndex];
nums[minIndex] = temp;
// 可能影响maxIndex
if(maxIndex == i) maxIndex = minIndex;
temp = nums[nums.length - i - 1];
nums[nums.length - i - 1] = nums[maxIndex];
nums[maxIndex] = temp;
}
return nums;
}
} 注意点:将最小值移动到左侧后,不能立即将最大值移动到右侧,因为当最大值在左侧待交换位置时,交换完成后,最大值的索引也应该更新。 |
Beta Was this translation helpful? Give feedback.
-
善用 STL,可以像伪代码一样清晰展现选择排序的原理,只要2行: // begin, end: ForwardIt
for (auto it = begin; it != end; ++it) {
std::iter_swap(it, std::min_element(it, end));
} |
Beta Was this translation helpful? Give feedback.
-
外层循环从1开始遍历是因为舍弃了第一项,全程都从数组第二项开始吗。? |
Beta Was this translation helpful? Give feedback.
-
https://oi-wiki.org/basic/selection-sort/
OI Wiki 是一个编程竞赛知识整合站点,提供有趣又实用的编程竞赛知识以及其他有帮助的内容,帮助广大编程竞赛爱好者更快更深入地学习编程竞赛
Beta Was this translation helpful? Give feedback.
All reactions