插入排序、堆排序、快速排序、冒泡排序,请用c++语言实现上述排序,写在同一个程序里,头文件里不包括vector、algorithm
时间: 2023-10-20 13:10:03 浏览: 67
几个排序算法的C++实现
以下是使用C++语言实现的四种排序算法:
```
#include <iostream>
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void heapify(int arr[], int n, int i) {
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
std::swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
std::swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[i + 1], arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
std::swap(arr[j], arr[j + 1]);
}
int main() {
const int len = 10;
int arr[len] = {5, 7, 1, 3, 9, 2, 8, 4, 6, 0};
insertionSort(arr, len);
std::cout << "Insertion Sort: ";
for (int i = 0; i < len; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
heapSort(arr, len);
std::cout << "Heap Sort: ";
for (int i = 0; i < len; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
quickSort(arr, 0, len - 1);
std::cout << "Quick Sort: ";
for (int i = 0; i < len; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
bubbleSort(arr, len);
std::cout << "Bubble Sort: ";
for (int i = 0; i < len; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
return 0;
}
```
阅读全文