数据结构顺序表实现直接插入排序、折半插入排序、希尔排序、快速排序、简单选择排序、堆排序、归并排序C语言代码完整
时间: 2024-01-09 21:05:04 浏览: 142
以下是数据结构顺序表实现直接插入排序、折半插入排序、希尔排序、快速排序、简单选择排序、堆排序、归并排序的C语言代码:
1. 直接插入排序:
```c
void InsertSort(int arr[], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
```
2. 折半插入排序:
```c
void BinaryInsertSort(int arr[], int n) {
int i, j, low, high, mid, temp;
for (i = 1; i < n; i++) {
temp = arr[i];
low = 0;
high = i - 1; while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] > temp) {
high = mid - 1;
} else {
low = mid + 1;
}
}
for (j = i - 1; j >= low; j--) {
arr[j + 1] = arr[j]; }
arr[low] = temp;
}
}
```
3. 希尔排序:
```c
void ShellSort(int arr[], int n) {
int i, j, gap, temp;
for (gap = n / 2; gap > 0; gap /= 2) {
for (i = gap; i < n; i++) {
temp = arr[i];
for (j = i - gap; j >= 0 && arr[j] > temp; j -= gap) {
arr[j + gap] = arr[j];
}
arr[j + gap] = temp;
}
}
}
```
4. 快速排序:
```c
int Partition(int arr[], int low, int high) {
int pivot = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivot) {
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) {
low++;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
void QuickSort(int arr[], int low, int high) {
if (low < high) {
int pivotPos = Partition(arr, low, high);
QuickSort(arr, low, pivotPos - 1);
QuickSort(arr, pivotPos + 1, high);
}
}
```
5. 简单选择排序:
```c
void SelectSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
```
6. 堆排序:
```c
void AdjustHeap(int arr[], int i, int n) {
int child, temp;
for (temp = arr[i]; 2 * i + 1 < n; i = child) {
child = 2 * i + 1;
if (child != n - 1 && arr[child] < arr[child + 1]) {
child++;
}
if (temp < arr[child]) {
arr[i] = arr[child];
} else {
break;
}
}
arr[i] = temp;
}
void HeapSort(int arr[], int n) {
int i, temp;
for (i = n / 2 - 1; i >= 0; i--) {
AdjustHeap(arr, i, n);
}
for (i = n - 1; i > 0; i--) {
temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
AdjustHeap(arr, 0, i);
}
}
```
7. 归并排序:
```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];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void MergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
MergeSort(arr, left, mid);
MergeSort(arr, mid + 1, right);
Merge(arr, left, mid, right);
}
}
```
阅读全文