class sort_algorithm
{
public:
int array[MAXN];
int n;
public:
sort_algorithm() { }
~sort_algorithm() { }
/*插入排序 复杂度O(n^2) 稳定排序*/
void Insertion_sort()
{
for (int i = 2; i <= n; i++)
{
int key = array[i];
int j = i - 1;
while (j >= 1 && array[j] > key)
{
array[j + 1] = array[j];
j--;
}
array[j + 1] = key;
}
}
//希尔排序 复杂度 O(nlog^2 n) 不稳定排序
void shell_sort()
{
for (int gap = n / 2; gap >= 1; gap >>= 1)
{
for (int i = gap; i <= n; i++)
{
int key = array[i];
int j = i - gap;
while (j >= 1 && array[j] > key)
{
array[j + gap] = array[j];
j -= gap;
}
array[j + gap] = key;
}
}
}
/*冒泡排序 复杂度O(n^2) 稳定排序*/
void bubble_sort()
{
for (int i = n; i >= 2; i--)
{
for (int j = 1; j <= i - 1; j++)
{
if (array[j + 1] < array[j])
swap(array[j], array[j + 1]);
}
}
}
/*优化版冒泡排序 复杂度O(n^2) 稳定排序*/
void bubble_sort2()
{
int bound = n;
while (bound != 0)
{
int t = 0;
for (int i = 1; i <= bound - 1; i++)
{
if (array[i] > array[i + 1])
swap(array[i], array[i + 1]);
t = i;
}
bound = t;
}
}
/*选择排序 复杂度O(n^2) 不稳定排序*/
void select_sort()
{
for (int i = n; i >= 2; i--)
{
int t = 1;
for (int j = 2; j <= i; j++)
{
if (array[t] < array[j])
t = j;
}
swap(array[t], array[i]);
}
}
/*归并排序 复杂度O(logn) 稳定排序*/
void merge(int l, int mid, int r)
{
int i = l, j = mid + 1;
int n = mid, m = r;
int k = 0;
int temp[MAXN];
while (i <= n && j <= m)
{
if (array[i] <= array[j])
temp[k++]= array[i++];
else temp[k++] = array[j++];
}
while (i <= n) temp[k++] = array[i++];
while (j <= m) temp[k++] = array[j++];
for (i = 0; i < k;i++)
array[l + i] = temp[i];
}
void merge_sort(int l, int r)
{
if (l < r)
{
int m = (l + r) >> 1;
merge_sort(l, m);
merge_sort(m + 1, r);
merge(l, m, r);
}
}
/*堆排序 复杂度 O(logn) 不稳定排序*/
void heapadjust(int i,int size)
{//建立递增序列,使用大根堆
int lson = i << 1;
int rson = i << 1|1;
int mx = i;
if(i <= size / 2)
{
if (lson <= size && array[lson] > array[mx])
mx = lson;
if (rson <= size && array[rson] > array[mx])
mx = rson;
if (mx != i)
{
swap(array[i], array[mx]);
heapadjust(mx,size);
}
}
}
void buildheap()
{
for (int i = n / 2; i >= 1; i--)
{
heapadjust(i, n);
}
}
void heap_sort()
{
buildheap();
for (int i = n; i >= 1; i--)
{
swap(array[1], array[i]);
heapadjust(1, i-1);
}
}
/*快速排序 复杂度O(logn) 不稳定排序*/
void quick_sort(int l, int r)
{
if (l < r)
{
int i = l, j = r, x = array[l];
while (i < j)
{
while (i < j && array[j] >= x) j--;
if (i < j) array[i++] = array[j];
while (i < j && array[i] < x) i++;
if (i < j) array[j--] = array[i];
}
array[i] = x;
quick_sort(l, i-1);
quick_sort(i + 1, r);
}
}
};
istream &operator >> (istream &is, sort_algorithm &item)
{
is >> item.n;
for (int i = 1; i <= item.n; i++)
is >> item.array[i];
return is;
}
ostream &operator << (ostream &os, const sort_algorithm &item)
{
os << item.n << endl;
for (int i = 1; i <= item.n; i++)
os << item.array[i] << ' ';
os << endl;
return os;
}
各种常见排序算法归纳总结
最新推荐文章于 2023-11-26 12:33:36 发布