公共函数,用以测试数组相等
namespace SortCommon {
bool ArrEqual(int arr1[], int arr2[], int n) {
for (int i = 0; i < n; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
}
冒泡排序
// O(N*N), 稳定排序
void BubbleSortTest(int arr[], int n) {
for (int i = n - 1; i > 0; --i) {
for (int j = 0; j < i; ++j) {
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]);
}
}
}
}
void test() {
int arr1[]{9, 3, 7, 6, 5, 1, 8, 2, 4};
int arr1r[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
BubbleSortTest(arr1, 9);
assert(SortCommon::ArrEqual(arr1, arr1r, 9) == true);
int arr2[]{1};
int arr2r[]{1};
BubbleSortTest(arr2, 1);
assert(SortCommon::ArrEqual(arr2, arr2r, 1));
int arr3[]{2, 1};
int arr3r[]{1, 2};
BubbleSortTest(arr3, 2);
assert(SortCommon::ArrEqual(arr3, arr3r, 2));
return;
}
希尔排序
// O(N*N), 不稳定排序,插入排序的优化,可以减少元素的移动交换
void ShellSortTest(int arr[], int n) {
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; ++i) {
int j = i;
while (j - gap >= 0 && arr[j] < arr[j - gap]) {
std::swap(arr[j], arr[j - gap]);
j -= gap;
}
}
}
}
void test() {
int arr1[]{9, 3, 7, 6, 5, 1, 8, 2, 4};
int arr1r[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
ShellSortTest(arr1, 9);
assert(SortCommon::ArrEqual(arr1, arr1r, 9) == true);
int arr2[]{1};
int arr2r[]{1};
ShellSortTest(arr2, 1);
assert(SortCommon::ArrEqual(arr2, arr2r, 1));
int arr3[]{2, 1};
int arr3r[]{1, 2};
ShellSortTest(arr3, 2);
assert(SortCommon::ArrEqual(arr3, arr3r, 2));
return;
}