Bubble sort to stack

I need to change my bubble sort (void stekas) to something called stack. Thing is that in file there are numbers and I need to sort them to rising order. I did good with bubble sort, but I have no idea how I should do that using stack. Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
 #include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>

using namespace std;

void stekas(int a[], int N)
{
   int temp;
   for(int i = 0; i < N; i++)
	{
		for(int j=0; j < N - 1 -i; j++)
		{
		   if(a[j] > a[j+1])
			{
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			}
		}
	}
}

int main()
{
	int i, j, temp, a[100];
	int N = 0;
	int value;
	
	ifstream file;

	char FailoVardas[100];
	cout << "Ivesk failo pavadinima: ";
	cin >>  FailoVardas;
	
	file.open (FailoVardas);
	
	if (!file.is_open())
        {
           cout << "Failas neatidarytas.... \n";
		   cin.get();
		   return 1;  
        }
        
	else
	{
		while (!file.eof())
	    {
		   file >> a[N];
		   N++;	
	    }
	}
        
    file.close();
	
  	
	cout << "\nPradiniai skaiciai \n";
	for( i = 0; i < N;  i++)
	{
		cout << a[i] << " " ;
	}

  	cout << endl;
  	
	stekas(a,N);	
	cout<<"\nDidejimo tvarka:\n ";
	for( i = 0; i < N;  i++)
	{
		cout<< a[i] << " ";
	}
	
	
    
    
    
return 0;		
}

You can't sort a stack because you can access only the top element. What you could do is copy all the elements from the stack into the array, sort the array and copy the array elements from the array to the stack. However if you need the elements sorted a stack might not be right container.

Is there a reason why you don't use vector and std::sort ?
No there isn't a reason. Also, I don't really understand what do you mean by copying it. :/
Like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
  stack<int> s;
  vector<int>v;

  // create a unsorted stack 
  for (int i: {1, 5, 3, 7, 2})
    s.push(i);

  // bring the numbers into the vector
  while (!s.empty())
  {
    v.push_back(s.top());
    s.pop();
  }
  // sort the vector
  sort(v.begin(), v.end());

  // add the numbers from the vector to the stack

  for (int i: v)
    s.push(i);

  // stack now should be sorted
  while (!s.empty())
  {
    cout << s.top() << "\t";
    s.pop();
  }
}

Topic archived. No new replies allowed.