Afficher un message
Vieux 17/10/2007, 03h50   #6
lovecreatesbea...@gmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Selection sort and bubble sort

On Oct 17, 7:22 am, user923005 <dcor...@connx.com> wrote:
> On Oct 16, 12:32 pm, "lovecreatesbea...@gmail.com"
>
> <lovecreatesbea...@gmail.com> wrote:
> > Selection sort and bubble sort have same performance always, right?

>
> Sort of. They are both O(n*n) but bubble sort has a larger constant
> of proportionality.
>
> > Are the following correctly implemented the both functions.

>
> No.
>
> > Comments
> > are welcome.

>
> news:comp.programming is the appropriate place for your question.
>


People use different language there, and I like the C code.

> [snip of icky[tm] sorts, insertion of nearly equally icky[tm] sorts:]
>
> #include <stdlib.h>
> #ifdef UNIT_TEST
> typedef int e_type;
> #else
> #include "e_type.h"
> #endif
>
> void selection_sort(e_type array[], size_t size)
> {
> size_t i,
> j,
> smallest;
> e_type tmp;
> for (i = 0; i < size - 1; i++) {
> smallest = i;
> for (j = i + 1; j < size; j++) {
> if (array[j] < array[smallest]) {
> smallest = j;
> }
> }
> tmp = array[i];
> array[i] = array[smallest];
> array[smallest] = tmp;
> }
>
> }
>


Your code does less exchange than mine (though an asterisk missed for
the parameter a).

> void bubble_sort(e_type * array, size_t length)
> {
> size_t i,
> j;
> e_type tmp;
> for (i = 0; i < length; i++) {
> for (j = 0; j < i; j++) {
> if (array[i] < array[j]) {
> tmp = array[i];
> array[i] = array[j];
> array[j] = tmp;
> }
> }
> }
>
> }
>
> #ifdef UNIT_TEST
> #include <stdio.h>
> #include <time.h>
>
> static e_type arr[65535];
> static size_t e_size = sizeof arr / sizeof arr[0];
>
> void sort_check(void)
> {
> size_t index;
> int failed = 0;
> for (index = 1; index < e_size; index++) {
> if (arr[index - 1] > arr[index]) {
> printf("Out of sort at %d where arr[%d]=%d > arr[%d]=%d
> \n", index, index - 1, arr[index - 1], index, arr[index]);
> failed = 1;
> }
> }
> if (failed)
> puts("Sort failed.");
> else
> puts("Sort succeeded.");
>
> }
>
> void mk_rand_arr(void)
> {
> size_t index;
> for (index = 0; index < e_size; index++) {
> arr[index] = rand();
> }
>
> }
>
> int main()


If UNIT_TEST isn't defined, the main() function is skipped. Your .c
file can compile but can't link, am I right?

> {
> time_t start;
> double delta;
> mk_rand_arr();
> puts("Selection Sort:");
> start = time(NULL);
> selection_sort(arr, e_size);
> delta = difftime(time(NULL), start);
> sort_check();
> printf("Elapsed time is %f\n", delta);
> mk_rand_arr();
> puts("Bubble Sort:");
> start = time(NULL);
> bubble_sort(arr, e_size);
> delta = difftime(time(NULL), start);
> printf("Elapsed time is %f\n", delta);
> sort_check();
> return 0;}
>
> #endif



  Réponse avec citation
 
Page generated in 0,23910 seconds with 9 queries