C 语言递归实现 冒泡 和 插入排序
1、冒泡排序递归实现:
源码如下:
void recurbublSort(int arr[], int len){
int temp;
if (len == 1){
return;
}
for (int i=0; i<len-1; i++){
if (arr[i] > arr[i+1]){
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
len=len-1;
recurbublSort(arr, len);
}
void printarr(int arr[], int len)
{
for(int i = 0; i < len; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
int main(){
int arr[] = {21, 34, 20, 31, 78, 43, 66};
int length = sizeof(arr)/sizeof(arr[0]);
printf("Unsorted arr : ");
printarr(arr, length);
recurbublSort(arr, length);
printf("Sorted array : ");
printarr(arr, length);
return 0;
}
编译运行输出为:
2、插入排序递归实现:
源码如下:
void recinsSort(int arr[], int n){
if (n <= 1)
return;
recinsSort( arr, n-1 );
int nth = arr[n-1];
int j = n-2;
while (j >= 0 && arr[j] > nth){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = nth;
}
void printarr(int arr[], int len)
{
for(int i = 0; i < len; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
int main(){
int arr[] = {21, 34, 20, 31, 78, 43, 66};
int length = sizeof(arr)/sizeof(arr[0]);
printf("Unsorted arr : ");
printarr(arr, length);
recinsSort(arr, length);
printf("Sorted array : ");
printarr(arr, length);
return 0;
}
编译运行输出为:
其他排序: