A
arnuld
Just wrote selection-sort in C. Is it the right way to do this in C ?
(definition of selection-sort taken from exercise 2.2-2 of Introduction
to Algorithms, 2e)
/* Exercise 2.2-2, page 29, Selection Sort */
#include <stdio.h>
enum { SIZE_ARR = 6 };
void selectionSort(char s[], int len);
int findSmallest(char s[], const int idx_cur, const int len);
int main(void)
{
char arr[SIZE_ARR+1] = {'a', 'r', 'n', 'u', 'l', 'd'};
printf("%s\n", arr);
selectionSort(arr, SIZE_ARR);
printf("%s\n", arr);
return 0;
}
void selectionSort(char s[], int len)
{
int i, idx;
char tmp;
for(i = 0; i != len; ++i)
{
idx = findSmallest(s, i, len);
/* printf("i = %d, Smallest Index = %d, s[%d] = %c\n", i, idx,
idx, s[idx]); */
tmp = s;
s = s[idx];
s[idx] = tmp;
}
}
int findSmallest(char s[], const int idx_cur, const int len)
{
int j, ret_index;
char smallest = s[idx_cur];
ret_index = idx_cur;
for(j = idx_cur+1; j != len; ++j)
{
/* printf("idx_cur = %d, j = %d\n", idx_cur, j); */
if(smallest > s[j])
{
smallest = s[j];
ret_index = j;
}
}
return ret_index;
}
===================== OUTPUT =======================
[arnuld@dune Intro-to-Algos]$ gcc -ansi -pedantic -Wall -Wextra 2.2-2.c
[arnuld@dune Intro-to-Algos]$ ./a.out
arnuld
adlnru
[arnuld@dune Intro-to-Algos]$
-- arnuld
www.LispMachine.Wordpress.com
(definition of selection-sort taken from exercise 2.2-2 of Introduction
to Algorithms, 2e)
/* Exercise 2.2-2, page 29, Selection Sort */
#include <stdio.h>
enum { SIZE_ARR = 6 };
void selectionSort(char s[], int len);
int findSmallest(char s[], const int idx_cur, const int len);
int main(void)
{
char arr[SIZE_ARR+1] = {'a', 'r', 'n', 'u', 'l', 'd'};
printf("%s\n", arr);
selectionSort(arr, SIZE_ARR);
printf("%s\n", arr);
return 0;
}
void selectionSort(char s[], int len)
{
int i, idx;
char tmp;
for(i = 0; i != len; ++i)
{
idx = findSmallest(s, i, len);
/* printf("i = %d, Smallest Index = %d, s[%d] = %c\n", i, idx,
idx, s[idx]); */
tmp = s;
s = s[idx];
s[idx] = tmp;
}
}
int findSmallest(char s[], const int idx_cur, const int len)
{
int j, ret_index;
char smallest = s[idx_cur];
ret_index = idx_cur;
for(j = idx_cur+1; j != len; ++j)
{
/* printf("idx_cur = %d, j = %d\n", idx_cur, j); */
if(smallest > s[j])
{
smallest = s[j];
ret_index = j;
}
}
return ret_index;
}
===================== OUTPUT =======================
[arnuld@dune Intro-to-Algos]$ gcc -ansi -pedantic -Wall -Wextra 2.2-2.c
[arnuld@dune Intro-to-Algos]$ ./a.out
arnuld
adlnru
[arnuld@dune Intro-to-Algos]$
-- arnuld
www.LispMachine.Wordpress.com