my task is to sort an array by the smallest digit of a number using selection sort. for example: 61 < 35, because 1 < 3. in case of coincidence of digits, i have to print the smallest of 2. so this is my code:
#include <iostream> #include <time.h> using namespace std; int smallestOfTwo(int a, int b) { if (a < b) return a; else return b; } int smallestDigit(int a) { int smallDigit = 9; while (a != 0) { if (a % 10 < smallDigit) { smallDigit = a % 10; } a /= 10; } return smallDigit; } void selectionSort(int arr[], const int size) { for (int i = 0; i < size - 1; i++) { int min = i; for (int j = i + 1; j < size; j++) { if (smallestDigit(arr[j]) == smallestDigit(arr[min])) min = smallestOfTwo(j, min); else if (smallestDigit(arr[j]) < smallestDigit(arr[min])) min = j; } if (min != i) { swap(arr[min], arr[i]); } } } int main() { srand(time(NULL)); const int size = 5; int arr[size]; for (int i = 0; i < size; i++) { arr[i] = rand() % 201; cout << arr[i] << " "; } cout << "\n--------------------------------------------------------------------------------------\n"; selectionSort(arr, size); for (int i = 0; i < size; i++) cout << arr[i] << " "; return 0; } the problem is that for some numbers it works (for example, for 23 63 70 37 183 the output is correct: 70 183 23 37 63), but for some it doesnt work(for example, 27 26 156 178 47. the output is 156 178 27 26 47, but it should be 156 178 26 27 47 instead) and i cant figure out why. any help would be appreciated. thanks!