分别采用直接插入排序,简单选择排序,冒泡排序,快速排序,归并排序的算法对给 定的线性表进行排序。C语言代码
时间: 2023-07-05 13:27:45 浏览: 73
排序代码(C语言),快速排序,冒泡排序,归并排序等等
好的,我可以给你介绍一下这些排序算法的C语言实现代码。以下是各个算法对线性表进行排序的代码示例:
1. 直接插入排序:
```c
void InsertSort(int a[], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
for (j = i - 1; j >= 0 && a[j] > temp; j--)
a[j + 1] = a[j];
a[j + 1] = temp;
}
}
```
2. 简单选择排序:
```c
void SelectSort(int a[], int n) {
int i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min]) min = j;
if (min != i) {
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}
```
3. 冒泡排序:
```c
void BubbleSort(int a[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
```
4. 快速排序:
```c
void QuickSort(int a[], int left, int right) {
int i, j, temp, pivot;
if (left < right) {
i = left;
j = right + 1;
pivot = a[left];
do {
do i++; while (a[i] < pivot);
do j--; while (a[j] > pivot);
if (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
} while (i < j);
temp = a[left];
a[left] = a[j];
a[j] = temp;
QuickSort(a, left, j - 1);
QuickSort(a, j + 1, right);
}
}
```
5. 归并排序:
```c
void Merge(int a[], int low, int mid, int high, int temp[]) {
int i = low, j = mid + 1, k = 0;
while (i <= mid && j <= high) {
if (a[i] < a[j]) temp[k++] = a[i++];
else temp[k++] = a[j++];
}
while (i <= mid) temp[k++] = a[i++];
while (j <= high) temp[k++] = a[j++];
for (i = 0; i < k; i++) a[low + i] = temp[i];
}
void MergeSort(int a[], int low, int high, int temp[]) {
if (low < high) {
int mid = (low + high) / 2;
MergeSort(a, low, mid, temp);
MergeSort(a, mid + 1, high, temp);
Merge(a, low, mid, high, temp);
}
}
void MergeSort(int a[], int n) {
int* temp = (int*)malloc(sizeof(int) * n);
MergeSort(a, 0, n - 1, temp);
free(temp);
}
```
希望这些代码能够对你有所帮助。
阅读全文