mardi 6 janvier 2015

Anyway to make this sorting algorithm more efficient/shorter C++


// Number Sorting Algorithm - Trey Taylor 2014
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;
int main() {
int numbersort [] = {200, 85, 63, 4}
cout << "The numbers scrambled are: ";
cout << numbersort[0] << ", ";
cout << numbersort[1] << ", ";
cout << numbersort[2] << ", ";
cout << numbersort[3] << ", " << endl;
firstlast:
if (numbersort[0] > numbersort[1]) {
int temp = 0;
temp = numbersort[0];
numbersort[0] = numbersort[1];
numbersort[1] = temp;
}
if (numbersort[1] > numbersort[2]) {
int temp = 0;
temp = numbersort[1];
numbersort[1] = numbersort[2];
numbersort[2] = temp;
}
if (numbersort[2] > numbersort[3]) {
int temp = 0;
temp = numbersort[2];
numbersort[2] = numbersort [3];
numbersort[3] = temp;
}
while (numbersort[0] > numbersort[1]) {
goto firstlast;
}
cout << "The numbers unscrambled are: ";
cout << numbersort[0] << ", ";
cout << numbersort[1] << ", ";
cout << numbersort[2] << ", ";
cout << numbersort[3] << ", ";
}


Does anybody know if there is a way to use a for or while loop to rearrange the numbers in the array into ascending order from left to right rather than just using 3 if statements


Aucun commentaire:

Enregistrer un commentaire