用c语言实现:直接插入排序,折半插入排序,冒泡排序,快速排序,简单选择排序。
时间: 2023-07-06 08:36:28 浏览: 133
好的,我可以回答你的问题,并为你提供这些算法的C语言实现。
1. 直接插入排序:
```c
void insertionSort(int arr[], int n) {
int i, j, key;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
```
2. 折半插入排序:
```c
void binaryInsertionSort(int arr[], int n) {
int i, j, key, low, high, mid;
for (i = 1; i < n; i++) {
key = arr[i];
low = 0;
high = i - 1;
while (low <= high) {
mid = (low + high) / 2;
if (key < arr[mid])
high = mid - 1;
else
low = mid + 1;
}
for (j = i - 1; j >= low; j--)
arr[j + 1] = arr[j];
arr[low] = key;
}
}
```
3. 冒泡排序:
```c
void bubbleSort(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;
}
}
}
}
```
4. 快速排序:
```c
void quickSort(int arr[], int low, int high) {
int i, j, pivot, temp;
if (low < high) {
pivot = low;
i = low;
j = high;
while (i < j) {
while (arr[i] <= arr[pivot] && i < high)
i++;
while (arr[j] > arr[pivot])
j--;
if (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[pivot];
arr[pivot] = arr[j];
arr[j] = temp;
quickSort(arr, low, j - 1);
quickSort(arr, j + 1, high);
}
}
```
5. 简单选择排序:
```c
void selectionSort(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[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
```
希望这些代码能够对你有所帮助!
阅读全文