buble sorting using clases

i want to know the problem in my code , its not working actually though in my compiler its even compiling the file but real problem lies in the results it just takes the input and shows a string of 0`s as the output :/ why is this so !

#include<iostream>
#include<conio.h>
using namespace std;
class sort
{
public:
int input();
int bubble_sort();
int print(); };

int main()
{

sort s1;
s1.input();
s1.bubble_sort();
s1.print();
}



int sort::input()
{ int n, i;
int* arr=new int[n];
cout<<"enter Num of Inputs"<<endl;
cin>>n;
cout<<"enter Integers"<<endl;
for(i=0; i<n; i++)
cin>>arr[n];
return arr[n];
}


int sort::bubble_sort()
{
int i, u, n, t;
int* arr=new int[n];
for(u=n; u>=1; u--)
for(i=0; i<=n; i++)
if(arr[i]>arr[i+1])
{
t=arr[i];
arr[i]=arr[i+1];
arr[i+1]=t;

} return arr[i+1]; }

int sort::print()
{ int i,n;
int* arr=new int[n];
cout<<"Sorted Values"<<endl;
for(i=0; i<=n; i++)
cout<<arr[n]<<endl;
return arr[n];
}
In any case some curly brackets are missing for the for loops in your bubble_sort function.
can u please mention in which line i m skipping the braces ?
Oups, I'm sorry, no curly bracket missing. But next time, you should format your code properly, 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<iostream>
#include<conio.h>

using namespace std;

class sort
{
   public:
      int input();
      int bubble_sort();
      int print();
};

int main()
{

   sort s1;
   s1.input();
   s1.bubble_sort();
   s1.print();
}

int sort::input()
{ 
   int n, i;
   int* arr=new int[n];
   cout<<"enter Num of Inputs"<<endl;
   cin>>n;
   cout<<"enter Integers"<<endl;
   for(i=0; i<n; i++)
      cin>>arr[n];

   return arr[n];
}


int sort::bubble_sort()
{
   int i, u, n, t;
   int* arr=new int[n];
   for(u=n; u>=1; u--)
      for(i=0; i<=n; i++)
         if(arr[i]>arr[i+1])
         {
            t=arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=t;

         } 
   return arr[i+1]; 
}

int sort::print()
{ 
   int i,n;
   int* arr=new int[n];
   cout<<"Sorted Values"<<endl;
   for(i=0; i<=n; i++)
      cout<<arr[n]<<endl;

   return arr[n];
}


Now I see the errors... In your print function, you write:

cout << arr[n] << endl;

It should be
cout << arr[i] << endl;

The other thing is your n variable. In your print and bubble_sort function, n is not initialized.
Maybe you should make it a member of your class. Do you see what I mean ?

One more thing, you cannot return arr[n] in your print function, because arr[n] is not defined (we count from 0). You could simply return 0;
Last edited on
Topic archived. No new replies allowed.