# Bubble sort is one of the simplest sorting algorithms used to sort data by comparing adjacent elements. All elements are compared in stages. The first stage puts the largest value at the end, the second stage puts the second largest element at the second to last position, and so on until the complete list is sorted.
p>
Input − Arr[] = { 5,7,2,3, 1,4}; length=6
Output − Sorted array: 1 2 3 4 5 7
Description −
First Pass 5 7 2 3 1 4 → swap → 5 2 7 3 1 4 5 2 7 3 1 4 → swap → 5 2 3 7 1 4 5 2 3 7 1 4 → swap → 5 2 3 1 7 4 5 2 3 1 7 4 → swap → 5 2 3 1 4 7 Second Pass 5 2 3 1 4 7 → swap → 2 5 3 1 4 7 2 5 3 1 4 7 → swap → 2 3 5 1 4 7 2 3 5 1 4 7 → swap → 2 3 1 5 4 7 2 3 1 5 4 7 → swap → 2 3 1 4 5 7 Third Pass 2 3 1 4 5 7 → swap → 2 1 3 4 5 7 2 1 3 4 5 7 no swap Fourth Pass 2 1 3 4 5 7 → swap → 1 2 3 4 5 7 1 2 3 4 5 7 no swap in further iterations
Input− Arr[] = { 1, 2, 3, 3, 2 };
Output− Sorted array: 1 2 2 3 3
Explanation -
First Pass 1 2 3 3 2 → swap → 1 2 3 2 3 1 2 3 2 3 → swap → 1 2 2 3 3 1 2 2 3 3 no swap in further iterations Second Pass 1 2 2 3 3 no swap in further iterations
< /p>
< /p>
#include <stdio.h> 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); } int main(){ int Arr[] = {21, 34, 20, 31, 78, 43, 66}; int length = sizeof(Arr)/sizeof(Arr[0]); recurbublSort(Arr, length); printf("Sorted array : "); for(int i=0;i<length;i++){ printf("%d ",Arr[i]); } return 0; }
Sorted array: 20 21 31 34 43 66 78
The above is the detailed content of C program for recursive bubble sort. For more information, please follow other related articles on the PHP Chinese website!