Bubble sort (Método burbuja).

#include "conio.h" #include <iostream> using namespace std; class Burbuja { private: double numeros[20]; public: int limite, iteraciones; Burbuja(); ~Burbuja(); void Ordenamiento(int,int); friend ostream& operator<<(ostream&, Burbuja*); friend istream& operator>>(istream&, Burbuja*); }; Burbuja::Burbuja() { iteraciones = 0; limite = 20; for(int i = 0; i < 20; i++) { numeros[i] = 0; } } Burbuja::~Burbuja() { iteraciones = 0; limite = 0; for(int i = 0; i < 20; i++) { numeros[i] = 0; } } void Burbuja::Ordenamiento(int contador, int tope) { double auxiliar = 0; if(contador + 1 < tope) { if(numeros[contador] > numeros[contador + 1]) { auxiliar = numeros[contador]; numeros[contador] = numeros[contador + 1]; numeros[contador + 1] = auxiliar; } Ordenamiento(++contador, tope); } else if(tope != 1) { cout << this; tope--; iteraciones++; Ordenamiento(0, tope); } } ostream& operator<<(ostream& output, Burbuja* o) { for(int i = 0; i < o->limite; i++) { if(i != 0) cout << ", "; cout << o->numeros[i]; } cout << endl; return output; } istream& operator>>(istream &input, Burbuja* o) { for(int i = 0; i < o->limite; i++) { cout << " Ingrese el numero " << i + 1 << ":" << endl << " >"; cin >> o->numeros[i]; } cout << endl << "Los datos ingresados son: " << o; return input; } int main() { Burbuja objeto; do { cout << "Ingrese la cantidad de datos a ingresar:" << endl << ">"; cin >> objeto.limite; if(objeto.limite > 20 || objeto.limite < 2) cout << "ERROR: Cantidad de datos no valida." << endl << "Debe ingresar por lo menos 2 numeros y maximo 20." << endl << endl; else break; } while(true); cout << endl << endl; cin >> &objeto; cout << endl << endl; objeto.Ordenamiento(0,objeto.limite); cout << endl << endl; cout << "Numero de iteraciones: " << objeto.iteraciones; _getch(); return 0; }
Here is some code for bubble sort. It's in Spanish but it works.

The limit of numbers is 20 and there is a "validation" part for when the user inputs the amount of numbers to order, so if the user writes a 1 it will give and error message and ask for other number to change the delimiter, and if the user gives a number bigger than 20 it won't work aswell.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.