//冒泡排序
void bubblesort(vector<int>& vec) {
int size = vec.size();
for (int i = size - 1; i > 0; i--) {
bool flag = false;
for (int j = 0; j < i; j++) {
if (vec[j] > vec[j + 1]) {
swap(vec[j], vec[j + 1]);
flag = true;
}
}
if (flag == false) break;
}
}
//选择排序
void selectionsort(vector<int>& vec) {
for (int i = 0; i < vec.size(); i++) {
for (int j = i + 1; j < vec.size(); j++) {
if (vec[j] < vec[i]) {
swap(vec[j], vec[i]);
}
}
}
}
//插入排序
void insertionsort(vector<int>& vec) {
for (int i = 1; i < vec.size(); i++) {
int j;
int daicharu = vec[i];
for (j = i - 1; j >= 0; j--) {
if (vec[j] > daicharu) {
vec[j + 1] = vec[j];
}
else break;
}
vec[j + 1] = daicharu;
}
}
//希尔排序
void shellsort(vector<int>& vec) {
int gap = vec.size() / 2;
while (gap) {
for (int i = gap; i < vec.size(); i += gap) {
int daicharu = vec[i];
int j;
for (j = i - gap; i >= 0; j -=gap) {
if (vec[j] > daicharu) {
vec[j + 1] = vec[j];
}
else break;
}
vec[j + gap] = daicharu;
}
gap = gap / 2;
}
}
//快速排序
void quicksort(vector<int>& vec, int left, int right) {
if (left >= right) {
return;
}
int i = left - 1;
int j = right + 1;
int x = vec[left + rand()%(right - left + 1)];
while (i < j) {
do i++; while (vec[i] < x);
do j--; while (vec[j] > x);
if (i < j) {
swap(vec[i], vec[j]);
}
else {
quicksort(vec, left, j);
quicksort(vec, j + 1, right);
}
}
}
//归并排序
void mergesort(vector<int>& vec, int left, int right) {
if (left >= right) {
return;
}
int mid = (left + right) / 2;
int i = left, j = mid + 1;
mergesort(vec, left, mid);
mergesort(vec, mid + 1, right);
vector<int> tmp;
while (i <= mid && j <= right) {
if (vec[i] < vec[j]) {
tmp.push_back(vec[i++]);
}
else {
tmp.push_back(vec[j++]);
}
}
while (i <= mid) {
tmp.push_back(vec[i++]);
}
while (j <= right) {
tmp.push_back(vec[j++]);
}
for (auto i : tmp) {
vec[left++] = i;
}
}
//堆排序:构造大顶堆,然后从后往前依次交换堆顶和数列最后一个元素,
//接着将最后一个元素从堆中移除,重新调整成大顶堆后,再次交换堆顶后最后一个元素。
void adjust(vector<int>& vec, int len, int index) {
int left = index * 2 + 1;
int right = index * 2 + 2;
int maxindex = index;
if (left < len && vec[left] > vec[maxindex]) maxindex = left;
if (right < len && vec[right] > vec[maxindex]) maxindex = right;
if (maxindex != index) {
swap(vec[index], vec[maxindex]);
adjust(vec, len, maxindex);
}
}
void heapsort(vector<int>& vec) {
int size = vec.size();
for (int i = size / 2 - 1; i >= 0; i--) {
adjust(vec, size, i);
}
for (int i = size - 1; i > 0; i--) {
swap(vec[0], vec[i]);
adjust(vec, i, 0);
}
}
void myprint(vector<int>& vec) {
for (auto i : vec) {
cout << i << " ";
}
cout << endl;
}
void main() {
vector<int> vec;
cout << "请输入要比较的数组大小:" << endl;
int n;
cin >> n;
cout << "请依次输入要比较的数:" << endl;
for (int i = 0; i < n; i++) {
int index;
cin >> index;
vec.push_back(index);
}
cout << "排序之前:" << endl;
myprint(vec);
heapsort(vec);
cout << "排序之后:" << endl;
myprint(vec);
return;
}
参考文章:
https://blog.csdn.net/mengyujia1234/article/details/90179896
https://blog.csdn.net/lzuacm/article/details/52853194