直接插入、折半插入、冒泡、快速、简单选择等排序方法 用c语言实现
时间: 2023-07-10 07:37:25 浏览: 88
C语言数据结构各种排序
3星 · 编辑精心推荐
好的,以下是几种排序算法的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, left, right, mid;
for (i = 1; i < n; i++) {
key = arr[i];
left = 0;
right = i - 1;
while (left <= right) {
mid = (left + right) / 2;
if (arr[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
for (j = i - 1; j >= left; j--) {
arr[j + 1] = arr[j];
}
arr[left] = 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 left, int right) {
int i, j, pivot, temp;
if (left < right) {
pivot = left;
i = left;
j = right;
while (i < j) {
while (arr[i] <= arr[pivot] && i < right) {
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, left, j - 1);
quickSort(arr, j + 1, right);
}
}
```
5. 简单选择排序
```c
void selectionSort(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;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
```
阅读全文