用C++写一个用回调函数,把数组a[10]={5,3,1,2,9,7,6,8,0,4};用冒泡法,选择排序,插入排序,快速排序这些方法对数组进行排序
时间: 2023-03-25 13:00:37 浏览: 71
回调函数的使用
使用回调函数的C程序,可以对数组a[10]={5,3,1,2,9,7,6,8,,4}进行冒泡排序、选择排序、插入排序和快速排序。
具体实现方法如下:
1. 冒泡排序
void bubble_sort(int *arr, int len, int (*cmp)(int a, int b))
{
int i, j, temp;
for (i = ; i < len - 1; i++)
{
for (j = ; j < len - i - 1; j++)
{
if (cmp(arr[j], arr[j + 1]) > )
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int cmp(int a, int b)
{
return a - b;
}
int main()
{
int a[10] = {5, 3, 1, 2, 9, 7, 6, 8, , 4};
bubble_sort(a, 10, cmp);
return ;
}
2. 选择排序
void selection_sort(int *arr, int len, int (*cmp)(int a, int b))
{
int i, j, min_index, temp;
for (i = ; i < len - 1; i++)
{
min_index = i;
for (j = i + 1; j < len; j++)
{
if (cmp(arr[j], arr[min_index]) < )
{
min_index = j;
}
}
if (min_index != i)
{
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
}
int cmp(int a, int b)
{
return a - b;
}
int main()
{
int a[10] = {5, 3, 1, 2, 9, 7, 6, 8, , 4};
selection_sort(a, 10, cmp);
return ;
}
3. 插入排序
void insertion_sort(int *arr, int len, int (*cmp)(int a, int b))
{
int i, j, temp;
for (i = 1; i < len; i++)
{
temp = arr[i];
j = i - 1;
while (j >= && cmp(arr[j], temp) > )
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
int cmp(int a, int b)
{
return a - b;
}
int main()
{
int a[10] = {5, 3, 1, 2, 9, 7, 6, 8, , 4};
insertion_sort(a, 10, cmp);
return ;
}
4. 快速排序
void quick_sort(int *arr, int left, int right, int (*cmp)(int a, int b))
{
if (left >= right)
{
return;
}
int i = left, j = right, pivot = arr[left];
while (i < j)
{
while (i < j && cmp(arr[j], pivot) >= )
{
j--;
}
if (i < j)
{
arr[i] = arr[j];
i++;
}
while (i < j && cmp(arr[i], pivot) <= )
{
i++;
}
if (i < j)
{
arr[j] = arr[i];
j--;
}
}
arr[i] = pivot;
quick_sort(arr, left, i - 1, cmp);
quick_sort(arr, i + 1, right, cmp);
}
int cmp(int a, int b)
{
return a - b;
}
int main()
{
int a[10] = {5, 3, 1, 2, 9, 7, 6, 8, , 4};
quick_sort(a, , 9, cmp);
return ;
}
阅读全文