手撕代码-基础排序算法

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; }

    推荐阅读