Liverpool_fan
Sami Hyypiä, LFC legend
All right.
First of all Bubble Sort is not exactly the most naturally expressed in recursive algorithm. However any iterative algorithm can be made recursive crudely at least. Is the following you desire?
I would still say at least iteratively compare the adjacent items in the function send_max_to_rear, the resulting code stuck with recursion only is very clumsy in my opinion, unless someone does it better.
P.S.: Divide and Conquer based algorithms are more suitable for recursive implementation, I'll suggest try QuickSort.
P.P.S.: Double test the code just in case, sleepy head you know.
First of all Bubble Sort is not exactly the most naturally expressed in recursive algorithm. However any iterative algorithm can be made recursive crudely at least. Is the following you desire?
I would still say at least iteratively compare the adjacent items in the function send_max_to_rear, the resulting code stuck with recursion only is very clumsy in my opinion, unless someone does it better.
PHP:
#include <stdio.h>
#define LEN 25
void send_max_to_rear(int *l, int pos, int len);
void pass(int *l, int len);
int main(void) {
int i;
int list[LEN];
for(i = 0; i < LEN; ++i) {
printf("Enter for %d: ", i+1);
scanf("%d", &list[i]);
}
pass(list, LEN);
for(i = 0; i < LEN; ++i) {
printf("%d ", list[i]);
}
puts(""); // Put a newline at the end of program's stdin
return 0;
}
void send_max_to_rear(int *l, int pos, int len) {
/*
This function sends the largest member of the sublist to the rear.
*/
/* Compare the members at `pos` and `pos+1` and swap if necessary */
if (l[pos] > l[pos+1]) {
int temp = l[pos];
l[pos] = l[pos+1];
l[pos+1] = temp;
}
/* As long as there are two elements to compare in the (sub)list, call compare the next two elements. */
if (pos < len - 2) {
send_max_to_rear(l, pos+1, len); // Move to the next position to compare.
}
}
void pass(int *l, int len) {
/*
This function recursively calls unsorted part of the list, after each pass.
*/
/* As long as array is has two unsorted elements, bubble sort it. */
if (len > 1 ) {
send_max_to_rear(l, 0, len);
pass(l, len - 1);
}
}
P.S.: Divide and Conquer based algorithms are more suitable for recursive implementation, I'll suggest try QuickSort.
P.P.S.: Double test the code just in case, sleepy head you know.