用C语言的顺序表实现直接插入排序、插入排序快、快速排序、希尔排序、冒泡排序、归并排序、堆排序怕算法比较。包括运行时间
时间: 2023-09-20 09:13:38 浏览: 113
由于运行时间与数据规模、数据分布等因素有关,因此在此无法给出具体的运行时间。以下是用C语言实现的各种排序算法的代码:
1. 直接插入排序
```c
void InsertionSort(int arr[], int n) {
int i, j, tmp;
for (i = 1; i < n; i++) {
tmp = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > tmp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = tmp;
}
}
```
2. 插入排序快
```c
int BinarySearch(int arr[], int left, int right, int x) {
int mid;
while (left <= right) {
mid = (left + right) / 2;
if (arr[mid] > x) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
void InsertionSortFast(int arr[], int n) {
int i, j, index, tmp;
for (i = 1; i < n; i++) {
tmp = arr[i];
j = i - 1;
index = BinarySearch(arr, 0, j, tmp);
while (j >= index) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = tmp;
}
}
```
3. 快速排序
```c
int Partition(int arr[], int left, int right) {
int pivot = arr[left];
while (left < right) {
while (left < right && arr[right] >= pivot) {
right--;
}
arr[left] = arr[right];
while (left < right && arr[left] <= pivot) {
left++;
}
arr[right] = arr[left];
}
arr[left] = pivot;
return left;
}
void QuickSort(int arr[], int left, int right) {
if (left < right) {
int pivotIndex = Partition(arr, left, right);
QuickSort(arr, left, pivotIndex - 1);
QuickSort(arr, pivotIndex + 1, right);
}
}
```
4. 希尔排序
```c
void ShellSort(int arr[], int n) {
int i, j, gap, tmp;
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
tmp = arr[i];
for (j = i - gap; j >= 0 && arr[j] > tmp; j -= gap) {
arr[j + gap] = arr[j];
}
arr[j + gap] = tmp;
}
}
}
```
5. 冒泡排序
```c
void BubbleSort(int arr[], int n) {
int i, j, tmp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
```
6. 归并排序
```c
void Merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
}
}
while (i < n1) {
arr[k++] = L[i++];
}
while (j < n2) {
arr[k++] = R[j++];
}
}
void MergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
MergeSort(arr, left, mid);
MergeSort(arr, mid + 1, right);
Merge(arr, left, mid, right);
}
}
```
7. 堆排序
```c
void Heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
int tmp = arr[i];
arr[i] = arr[largest];
arr[largest] = tmp;
Heapify(arr, n, largest);
}
}
void HeapSort(int arr[], int n) {
int i;
for (i = n / 2 - 1; i >= 0; i--) {
Heapify(arr, n, i);
}
for (i = n - 1; i >= 0; i--) {
int tmp = arr[0];
arr[0] = arr[i];
arr[i] = tmp;
Heapify(arr, i, 0);
}
}
```
阅读全文