Hello Everyone, Can anyone suggest me tutorial of selection sort where I can check the implementation code to selection sort in C?
Hello Everyone, Can anyone suggest me tutorial of selection sort where I can check the implementation code to selection sort in C?
Is Google not working?
selection sort in c - Google Search
Third hit for me looks OK:
Selection sort in C | Programming Simplified
Code:#include <stdio.h> #define ub(x) sizeof(x)/sizeof(x[0]) int arr[] = { 64, 25, 12, 4, 101, 22, 11 }; int smallest = 0, selection = 0; void getSmallest() { smallest = 0; for (int y=0; y<ub(arr); y++) { if (arr[y] < smallest || smallest == 0) { if (arr[y] != 0) { smallest = arr[y]; selection = y; } } } printf( "%i,", smallest ); } int main( int argc, char *argv[] ) { for (int i=0; i<ub(arr); i++) { getSmallest(); arr[selection] = 0; } printf( "\n" ); return 0; }
"without goto we would be wtf'd"
Selection sort... walk through the first element to the last but one (i). Inside that loop, walk to the second element to the last (j). Compare element at position i to the element at position j. If your criteria is "less than", then if element j is "less than" element i, swap them. That's it.
criteria is pointer to a function which returns -1, 0 or 1 (if 1, swap is made).Code:void selectionSort( void *ptr, // pointer to array size_t nelems, // num of elements in array size_t size, // size of each element int (*criteria)(void *, void *) // sorting criteria. ) { size_t i, j; void *tmp = malloc( size ); for ( i = 0; i < nelems - 1; i++ ) for ( j = 1; j < nelems; j++ ) if ( criteria( ptr + i*size, ptr + j*size ) > 0 ) { memcpy( tmp, ptr + i*size, size ); memcpy( ptr+i*size, ptr+j*size, size ); memcpy( ptr+j*size, tmp, size ); } free( tmp ); }
PS: void pointers (by ISO) behave as if they were char pointers, with pointer arithmetic.
Usage:
Code:int a[] = { 1, 10, 3, 4, -1, -13, 7 }; int criteria( void *a, void *b ) { return (*(int *)a > *(int *)b) - (*(int *)a < *(int *)b); } ... selectionSort( a, sizeof a/sizeof a[0], sizeof a[0], criteria );
Last edited by flp1969; 06-14-2021 at 07:55 AM.
Code:#include <stdio.h> #define ub(x) sizeof(x)/sizeof(x[0]) void selectionsort( int array[], int arraySize ) { for (int j=0; j<arraySize; j++) { int smallest = 0, selection = 0; int tmpBase = array[j]; for (int i=j; i<arraySize; i++) { if (smallest == 0 || smallest > array[i]) { smallest = array[i]; selection = i; } } array[j] = array[selection]; array[selection] = tmpBase; } } int main( int argc, char *argv[] ) { int arr[] = { 64, 25, 12, 4, 101, 22, 11 }; selectionsort( arr, ub(arr) ); for (int i=0; i<ub(arr); i++) { printf( "%i,", arr[i] ); } printf( "\n" ); return 0; }
"without goto we would be wtf'd"
Thanks for providing a sample. I have checked this on <<spam site removed>>
Last edited by Salem; 06-15-2021 at 12:43 AM. Reason: Removed spam site, answering your own question with a spam site is bad form