A
arnuld
To sort an array of characters using Bubble-Sort algorithm.
WANTED: To sort an array using Bubble Sort algorithm
GOT: ..
Can I improve C implementation of this ? I got this algorithm from
section 8.2 of "Data Structures and Algorithms by Aho, Hopcraft and
Ullman". I was wondering if I could simply use pointers instead of those
integer couters and array indexing:
/* A C program to sort an array of characters using bubble sort algorithm
*
* VERSION 0.0
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort_bubble(char* );
void swap_elements(char*, char* );
int main(void)
{
char arrc[] = "heathfield";
printf("array(unsorted): %s\n", arrc);
sort_bubble(arrc);
printf("array(sorted): %s\n", arrc);
return 0;
}
void sort_bubble(char* c)
{
size_t i, j;
size_t s = strlen(c);
for(i = 0; i < s; ++i)
{
for(j = s-1; j != i; --j)
{
/* printf("c[%d] = %c, c[%d] = %c\n", j, c[j], j-1, c
[j-1]); */
if( c[j] < c[j-1] ) swap_elements( &c[j], &c[j-1]);
}
}
}
void swap_elements(char* c1, char* c2)
{
char temp = *c1;
*c1 = *c2;
*c2 = temp;
}
=============== OUTPUT ======================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra bubble-sort.c
[arnuld@dune programs]$ ./a.out
array(unsorted): heathfield
array(sorted): adeefhhilt
[arnuld@dune programs]$
WANTED: To sort an array using Bubble Sort algorithm
GOT: ..
Can I improve C implementation of this ? I got this algorithm from
section 8.2 of "Data Structures and Algorithms by Aho, Hopcraft and
Ullman". I was wondering if I could simply use pointers instead of those
integer couters and array indexing:
/* A C program to sort an array of characters using bubble sort algorithm
*
* VERSION 0.0
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort_bubble(char* );
void swap_elements(char*, char* );
int main(void)
{
char arrc[] = "heathfield";
printf("array(unsorted): %s\n", arrc);
sort_bubble(arrc);
printf("array(sorted): %s\n", arrc);
return 0;
}
void sort_bubble(char* c)
{
size_t i, j;
size_t s = strlen(c);
for(i = 0; i < s; ++i)
{
for(j = s-1; j != i; --j)
{
/* printf("c[%d] = %c, c[%d] = %c\n", j, c[j], j-1, c
[j-1]); */
if( c[j] < c[j-1] ) swap_elements( &c[j], &c[j-1]);
}
}
}
void swap_elements(char* c1, char* c2)
{
char temp = *c1;
*c1 = *c2;
*c2 = temp;
}
=============== OUTPUT ======================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra bubble-sort.c
[arnuld@dune programs]$ ./a.out
array(unsorted): heathfield
array(sorted): adeefhhilt
[arnuld@dune programs]$