用C语言在一个程序中实现数据结构的多种排序方法
时间: 2024-02-05 21:14:03 浏览: 66
好的,以下是使用C语言实现数据结构的多种排序方法的示例代码:
```c
#include <stdio.h>
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void selectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min_index = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[min_index])
{
min_index = j;
}
}
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
void insertionSort(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (int i = 0; i < n1; i++)
{
L[i] = arr[l + i];
}
for (int j = 0; j < n2; j++)
{
R[j] = arr[m + 1 + j];
}
int i = 0, j = 0, k = l;
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 l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
if (arr[j] < pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main()
{
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
bubbleSort(arr, n);
printf("Bubble sorted array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
int arr2[] = { 64, 25, 12, 22, 11 };
selectionSort(arr2, n);
printf("Selection sorted array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr2[i]);
}
printf("\n");
int arr3[] = { 64, 25, 12, 22, 11 };
insertionSort(arr3, n);
printf("Insertion sorted array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr3[i]);
}
printf("\n");
int arr4[] = { 64, 25, 12, 22, 11 };
mergeSort(arr4, 0, n - 1);
printf("Merge sorted array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr4[i]);
}
printf("\n");
int arr5[] = { 64, 25, 12, 22, 11 };
quickSort(arr5, 0, n - 1);
printf("Quick sorted array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr5[i]);
}
printf("\n");
return 0;
}
```
以上代码演示了常见的五种排序方法:冒泡排序、选择排序、插入排序、归并排序和快速排序。您可以根据需要进行修改和扩展。
阅读全文