RECURSION EXERCISES 1
(递归练习1)
前言:资质驽钝,刚刚学习递归的时候总是感觉有点空洞,悬乎。
可能没有足够例题练练手。最近找了几道有难度层次的递归例题,在此分享给大家。
- Selection Sort(选择排序):A selection sort searches an array looking for the smallest element in the array. When the smallest element is found, it is swapped with the first element of the array. The process is then repeated for the subarray beginning with the second element of the array. Each pass of the array results in one element being placed in its proper location. This sort requires similar processing capabilities to the bubble sort—for an array of n elements, n– 1 passes must be made, and for each subarray, n– 1 comparisons must be made to find the smallest value. When the subarray being processed contains one element, the array is sorted. Write a recursive function selectionSortto perform this algorithm.
(大意就是要求写一个递归函数 selectionSort 来实现选择排序)<span style="color:#333333;">#include <stdio.h> void selectionSort(int a[], int start, int last); int main() { int a[10]; int i; printf("enter 20 numbers to compare: \n"); for (i = 0; i < 10; i++) { scanf("%d", &a[i]); } selectionSort(a, 0, 9); for (i = 0; i < 10; i++) { printf("%d ", a[i]); } printf("\n"); return 0; } void selectionSort(int a[], int start, int last) { int min; int j; int which = start; if (start == last) { return; } min = a[start]; for (j = start; j <= last; j++) { if (a[j] < min) { min = a[j]; which = j; } } a[which] = a[start]; a[start] = min; selectionSort(a, start + 1, last); }</span><span style="color:#cc9933;"> </span>
(先码代码,具体讲解等有空再码^_^)