0.交换元素方法
private void Swap(ref int a, ref int b) {
var temp = a;
a = b;
b = temp;
}
1.冒泡排序
public int[] BubbleSort(int[] originInts) {
if (originInts == null || originInts.Length == 0) {
return null;
}
int length = originInts.Length;
for (int i = 0;
i < length - 1;
i++) {
for (int j = i + 1;
j < length;
j++) {
if (originInts[i] > originInts[j]) {
Swap(ref originInts[i], ref originInts[j]);
}
}
}
return originInts;
}
2.快速排序
【手撕代码-基础排序算法】步骤①选中枢点②排序并返回中枢点③给字段排序
public int[] QuickSort(int[] originInts) {
if (originInts == null || originInts.Length == 0) {
return null;
}
int length = originInts.Length;
SubQuickSort(originInts, 0, length - 1);
return originInts;
}private void SubQuickSort(int[] originInts, int leftIndex, int rightIndex) {
if (leftIndex > rightIndex) {
return;
}
int partitionIndex = SortAndPartition(originInts, leftIndex, rightIndex);
SubQuickSort(originInts, leftIndex, partitionIndex - 1);
SubQuickSort(originInts, partitionIndex + 1, rightIndex);
}private int SortAndPartition(int[] originInts, int leftIndex, int rightIndex) {
int p = leftIndex;
int q = rightIndex;
int pivotValue = https://www.it610.com/article/originInts[rightIndex];
//对比锚点为队尾,此时队头的哨兵先移动
while (p != q) {//终止的条件为两哨兵相遇,此时与锚点交换位置
while (originInts[p] <= pivotValue && p < q) {//队头哨兵找到第一个比锚点大的点
p++;
}
while (originInts[q]>= pivotValue && p < q) {//队尾哨兵找到第一个比锚点小的点或者遇到了队头哨兵
q--;
}
if (p < q) {//两哨兵还没有相遇,交换数据之后继续向对方探测
Swap(ref originInts[p], ref originInts[q]);
}
}
//完成第一次排序
Swap(ref originInts[p], ref originInts[rightIndex]);
return p;
}
推荐阅读
- leetCode-Find All Numbers Disappeared in an Array
- leetcode42. Trapping Rain Water
- leetcode 42. Trapping Rain Water
- 蓝桥杯13-20届真题解析|蓝桥杯就要开赛了,填空题还不会(我教你一篇学会填空题,从此填空满分,信心大涨)
- 202. Happy Numberleetcodejava,hashSet,算法
- LeetCode - 448. Find All Numbers Disappeared in an Array
- [LeetCode] Happy Number
- LeetCode - Trapping Rain Water
- 一起刷好题|LeetCode刷题计划——单调数列