用c++编程实现 InsertSort、BubbleSort、QuickSort 和 SelectSort 等算法。
时间: 2024-05-12 09:19:20 浏览: 63
以下是使用C语言实现四种排序算法的代码示例:
1.插入排序(InsertSort)
```c
void insert_sort(int arr[], int n)
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = arr[i];
for (j = i-1; j >= 0 && arr[j] > temp; j--)
arr[j+1] = arr[j];
arr[j+1] = temp;
}
}
```
2.冒泡排序(BubbleSort)
```c
void bubble_sort(int arr[], int n)
{
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
```
3.快速排序(QuickSort)
```c
void quick_sort(int arr[], int left, int right)
{
int i = left, j = right;
int pivot = arr[(left+right)/2];
while (i <= j) {
while (arr[i] < pivot) i++;
while (arr[j] > pivot) j--;
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (left < j) quick_sort(arr, left, j);
if (i < right) quick_sort(arr, i, right);
}
```
4.选择排序(SelectSort)
```c
void select_sort(int arr[], int n)
{
int i, j, min_idx, temp;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
```
阅读全文