|
| 1 | +#include <stdio.h> |
| 2 | + |
| 3 | +//Following function will sort the array in Increasing (ascending) order |
| 4 | +void selection_sort(int arr[], int n) |
| 5 | +{ |
| 6 | + int i, j, tmp; |
| 7 | + |
| 8 | + /* advance the position through the entire array */ |
| 9 | + /* (could do i < n-1 because single element is also min element) */ |
| 10 | + for (i = 0; i < n-1; i++) |
| 11 | + { |
| 12 | + // find the min element in the unsorted a[i .. n-1] |
| 13 | + |
| 14 | + int current_Min = i; // assume the min is the first element |
| 15 | + // test against elements after i to find the smallest |
| 16 | + for ( j = i+1; j < n; j++) |
| 17 | + { |
| 18 | + // if this element is less, then it is the new minimum |
| 19 | + if (arr[j] < arr[current_Min]) //To sort in decreasing order just change the comparison operator to '>' |
| 20 | + { |
| 21 | + current_Min = j; // found new minimum; remember its index |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + if(current_Min != i) //if the current_Min is equal to i, then it is in right position already |
| 26 | + { |
| 27 | + //Swap the values |
| 28 | + tmp = arr[i]; |
| 29 | + arr[i] = arr[current_Min]; |
| 30 | + arr[current_Min] = tmp; |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +void print_list(int arr[], int num_of_element) |
| 36 | +{ |
| 37 | + int i; |
| 38 | + for(i = 0; i < num_of_element; i++) |
| 39 | + { |
| 40 | + printf("%d ", arr[i]); |
| 41 | + } |
| 42 | + |
| 43 | + printf("\n"); |
| 44 | +} |
| 45 | + |
| 46 | +int main(int argc, char const *argv[]) |
| 47 | +{ |
| 48 | + int arr[] = {43, 1, 24, 56, 30, 5}; |
| 49 | + int num_of_element = sizeof(arr)/sizeof(int); |
| 50 | + |
| 51 | + printf("Initial List:\n"); |
| 52 | + print_list(arr, num_of_element); |
| 53 | + |
| 54 | + selection_sort(arr, num_of_element); |
| 55 | + |
| 56 | + printf("Sorted list in ascending order: \n"); |
| 57 | + print_list(arr, num_of_element); |
| 58 | + |
| 59 | + return 0; |
| 60 | +} |
0 commit comments