online: 6; azi: 180; total: 52186 Manual clasa a xi a - Implementarea structurilor de date - Lista liniara

Probleme Rezolvate



Manual clasa a Xi a

Implementarea structurilor de date

Lista liniara

Se ordonează crescător un şir de numere, cu ajutorul a două stive. Determinați complexitatea algoritmului. (Indicație. Se folosesc două stive. Se scrie un număr în Stiva 1. Se citeşte un număr. Dacă numărul din vârful Stivei 1 este mai mare decât numărul citit, atunci noul număr se adaugă la Stiva 1; altfel, se descarcă din Stiva 1 în Stiva 2 numere până când în vârful Stivei 1 ajunge un număr mai mare decât numărul citit, se adaugă la Stiva 1 numărul citit, şi se încarcă în Stiva 1 numerele din Stiva 2.)
# include < iostream >
# include < fstream >
# define MAX_SIZE 100
using namespace std ;
int stack [MAX_SIZE];
int top = -1 ;
void push ( int num) {
if (top == MAX_SIZE - 1 ) {
cout << "Stiva este plina!" << endl ;
} else {
stack [++top] = num;
}
}
int pop () {
if (top == -1 ) {
cout << "Stiva este goala!" << endl ;
return -1 ;
} else {
return stack [top--];
}
}
bool is_empty () {
return top == -1 ;
}
void sort_numbers () {
int temp [MAX_SIZE], i, j;
int n = top + 1 ;
for (i = 0 ; i < n; i++) {
temp [i] = pop ();
}
for (i = 0 ; i < n; i++) {
int x = temp [i];
for (j = i + 1 ; j < n; j++) {
if ( temp [j] > x) {
x = temp [j];
}
}
push (x);
for (j = i; j < n; j++) {
if ( temp [j] != x) {
push ( temp [j]);
}
}
}
}
void print_stack () {
if ( is_empty ()) {
cout << "Stiva este goala!" << endl ;
} else {
for ( int i = top; i >= 0 ; i--) {
cout << stack [i] << " " ;
}
cout << endl ;
}
}
int main () {
int num;
// Citim stiva dintr-un fisier text
ifstream in ( "input.txt" ) ;
while (in >> num) {
push (num);
}
in. close ();
// Sortam stiva
sort_numbers ();
// Afisam stiva sortata
print_stack ();
return 0 ;
}
# include < iostream >
# include < fstream >
# include < stack >
using namespace std ;
void sort_numbers ( stack < int >& s) {
stack < int > temp ;
while (! s. empty ()) {
int num = s. top ();
s. pop ();
while (! temp. empty () && temp. top () > num) {
s. push ( temp. top ());
temp. pop ();
}
temp. push (num);
}
while (! temp. empty ()) {
s. push ( temp. top ());
temp. pop ();
}
}
int main () {
stack < int > s;
int num;
// Citim stiva dintr-un fisier text
ifstream in ( "input.txt" ) ;
while (in >> num) {
s. push (num);
}
in. close ();
// Sortam stiva
sort_numbers (s);
// Afisam stiva sortata
while (! s. empty ()) {
cout << s. top () << " " ;
s. pop ();
}
cout << endl ;
return 0 ;
}