冒泡排序
稳定性: 稳定
最好时间复杂度: O(n)基本有序的话不用交换直接比较一遍元素就好了
最坏时间复杂度: O(n^2)
空间复杂度: O(1)
void Bubble_Sort() {
for (int i = N-1; i >= 0; i--) {
int flag = 0;
for (int j = 1; j < i; j++) {
if (A[j] > A[j + 1]) {
swap(A[j], A[j + 1]);
flag = 1;
}
}
if (flag == 0) return;
}
}
快速排序
稳定性: 不稳定
最好时间复杂度: O(nlog n)
最坏时间复杂度: O(n^2)
空间复杂度: O(log n)或者 O(n)
int Partition(int low,int high) {
int pivot = A[low];
while (low < high) {
while (low < high&&A[high] >= pivot) high--;
A[low] = A[high];
while (low < high && A[low] <= pivot) low++;
A[high] = A[low];
}
A[high] = pivot;
return high;
}
void Partition_Sort(int low,int high) {
if (low >= high) return;
int pivot = Partition(low,high);
Partition_Sort(low, pivot - 1);
Partition_Sort(pivot + 1, high);
}