A
arnuld
It works fine. The Ullman's book does not have the check for (j > 0) in
inner loop which I have put myself. Any advice for improvement ?
One thing I don't get is how it is less expansive than bubble sort, we
have 2 loops and we exchange values and we do it only once. The only
difference is bubble starts for the bottom while insertion sort start
from the top but numbers of iterations are same.
/* A C program to learn insertion sort algorithm
*
* VERSION 0.0
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort_insertion(char* );
int main(void)
{
char arrc[] = "kandr";
printf("array(unsorted): %s\n", arrc);
sort_insertion(arrc);
printf("array(sorted): %s\n", arrc);
return 0;
}
void sort_insertion(char c[])
{
size_t i,j;
const size_t s = strlen(c);
if( 0 == s )
{
printf("oops!, nothing to sort\n");
return;
}
/* leave the first element for comparison, basis of insertion sort */
for(i = 1; i != s; ++i)
{
for(j = i; (j > 0) && (c[j] < c[j - 1]); --j)
{
char temp = c[j];
c[j] = c[j - 1];
c[j - 1] = temp;
}
}
}
=================== OUTPUT ==================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra insertion-sort.c
[arnuld@dune programs]$ ./a.out
array(unsorted): kandr
array(sorted): adknr
[arnuld@dune programs]$
inner loop which I have put myself. Any advice for improvement ?
One thing I don't get is how it is less expansive than bubble sort, we
have 2 loops and we exchange values and we do it only once. The only
difference is bubble starts for the bottom while insertion sort start
from the top but numbers of iterations are same.
/* A C program to learn insertion sort algorithm
*
* VERSION 0.0
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort_insertion(char* );
int main(void)
{
char arrc[] = "kandr";
printf("array(unsorted): %s\n", arrc);
sort_insertion(arrc);
printf("array(sorted): %s\n", arrc);
return 0;
}
void sort_insertion(char c[])
{
size_t i,j;
const size_t s = strlen(c);
if( 0 == s )
{
printf("oops!, nothing to sort\n");
return;
}
/* leave the first element for comparison, basis of insertion sort */
for(i = 1; i != s; ++i)
{
for(j = i; (j > 0) && (c[j] < c[j - 1]); --j)
{
char temp = c[j];
c[j] = c[j - 1];
c[j - 1] = temp;
}
}
}
=================== OUTPUT ==================
[arnuld@dune programs]$ gcc -ansi -pedantic -Wall -Wextra insertion-sort.c
[arnuld@dune programs]$ ./a.out
array(unsorted): kandr
array(sorted): adknr
[arnuld@dune programs]$