Download presentation
Presentation is loading. Please wait.
Published byCalvin Barnett Modified over 6 years ago
1
Selection Sort Find the smallest value in the array. Put it in location zero. Find the second smallest value in the array and put it in location 1. Find the kth smallest value and put in location k. Example: original: pass 1: pass 2:
2
Selection Sort After the second pass nothing changes of a third pass is done. This is a naturally recursive algorithm. Example: original: pass 1: pass 2: pass 3:
3
/* Recursive function to selection sort the elements of an array */
void selection(float orig_array[], int start, int size) { /* i is a loop index, sindex stores the index of the smallest number, temp is a temp variable and smallest is the smallest value found */ int i, sindex = start; float temp, smallest = orig_array[start]; /* The stopping condition */ if (start == size-1) printf("Finished sorting\n\n"); else { /* Find the smallest */ for (i=start+1; i< size; i++){ if (smallest > orig_array[i]){ smallest = orig_array[i]; sindex = i; } }
4
temp = orig_array[start]; orig_array[start] = orig_array[sindex];
/* swap them */ temp = orig_array[start]; orig_array[start] = orig_array[sindex]; orig_array[sindex] = temp; /* Put one in final place, do the next */ selection(orig_array, ++start, size); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.