设计递归算法实现简单的数据递增排序。 利用递归思想,选择简单选择或冒泡排序算法,实现一组数据的递增排序。给出代码
时间: 2024-01-24 09:16:47 浏览: 24
以下是使用递归实现冒泡排序的代码示例:
```
void bubbleSortRecursive(int arr[], int n) {
// base case
if (n == 1)
return;
// One pass of bubble sort. After this pass, the largest element is moved (or bubbled) to end.
for (int i=0; i<n-1; i++)
if (arr[i] > arr[i+1])
swap(arr[i], arr[i+1]);
// Largest element is fixed, recur for remaining array
bubbleSortRecursive(arr, n-1);
}
```
以下是使用递归实现选择排序的代码示例:
```
void selectionSortRecursive(int arr[], int n) {
// base case
if (n <= 1)
return;
// Find maximum element and swap it with the last element
int max_idx = 0;
for (int i=1; i<n; i++)
if (arr[i] > arr[max_idx])
max_idx = i;
swap(arr[max_idx], arr[n-1]);
// Recur for remaining array
selectionSortRecursive(arr, n-1);
}
```