A number is entered, it is necessary to get the minimum by rearranging its digits.

I implemented it, only it works incorrectly for me if the number is 0.

Help to implement, please.

#include <iostream> #include <cstring> using namespace std; void sort(string &s) { for(int a = 1; a < s.length(); a++) { for(int b = s.length() - 1; b >= a; b--) { if(s[b-1] > s[b] && !(s[b] == '0' && b - 1 == 0)) swap(s[b-1], s[b]); } } } int main() { string a; cin >> a; sort(a); cout << a << endl; system("pause"); return 0; } 

    2 answers 2

    If zeros at the beginning are prohibited, do this:

    1. Sort the numbers ascending
    2. If you get a zero at the beginning, find the first non-zero, and swap it with the first zero

    If the first non-zero in the second step was not found, your number was 0, and then everything is fine.

    • Exactly, thank you - risonyo
    • @risonyo: please! - VladD

    In this case, the bubble sort method is very suitable. Further I give an example:

      #include <iostream> using namespace std; // наш массив int array[100]; // сортировка void*Sort(int col) { // врСмСнная пСрСмСнная для хранСния ΠΏΡ€ΠΎΠΌΠ΅ΠΆΡƒΡ‚ΠΎΡ‡Π½ΠΎΠ³ΠΎ Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚Π° int trash=0; // ΠΏΠΎΠΊΠ° Π½Π΅ Ρ€Π°Π²Π½ΠΎ количСству Π΅Π»Π΅ΠΌΠ΅Π½Ρ‚ΠΎΠ² for (int i=1; i<=col ; i++) { // ΠΏΠΎΠΊΠ° Π½Π΅ Ρ€Π°Π²Π½ΠΎ col-i for (int j=1; j<=col-i; j++) { // Ссли Π»Π΅Π²Ρ‹ΠΉ элСмСнт большС if (array [j]>array [j+1]) { // ΠΏΡ€Π°Π²ΠΎΠ³ΠΎ, Ρ‚ΠΎ мСняСм ΠΈΡ… мСстами trash=array[j]; array [j]=array [j+1]; array [j+1]=trash; } } } } // Π²Ρ‹Π²ΠΎΠ΄ Π½Π° экран нашСго массива послС сортировки void*Out(int col) { for (int i=1; i<=col; i++) cout << array [i] <<" "; cout << endl; } int main() { int col_el; cout << " Enter length of array"<< endl; // считываСм количСство элСмСнтов cin >> col_el; // считываСм элСмСнты массива for (int n=1; n<=col_el ; n++) cin >> array[n]; Sort(col_el); // сортируСм ΠΈΡ… cout << "Result is :"<<endl; // ΠΈ Π²Ρ‹Π²ΠΎΠ΄ΠΈΠΌ Out(col_el); // ΠΆΠ΄Π΅ΠΌ наТатия клавиши cin >> col_el; return 0; } 
    • one
      I think TC knows how to sort by bubble. The problem was in the initial zeros. - VladD