0% found this document useful (0 votes)
49 views4 pages

Prepared by Dr/Kadry Ali 1 Method: #Include Using Namespace: STD

The document describes two methods for sorting an array using bubble sort in C++. The first method defines a fixed size array of 5 elements, takes user input to populate the array, and then performs bubble sort on the array displaying the sorted output. The second method improves on the first by making the array size dynamic based on user input, and using fewer lines of code to sort the array in-place. The document concludes that the second method is better than the first.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views4 pages

Prepared by Dr/Kadry Ali 1 Method: #Include Using Namespace: STD

The document describes two methods for sorting an array using bubble sort in C++. The first method defines a fixed size array of 5 elements, takes user input to populate the array, and then performs bubble sort on the array displaying the sorted output. The second method improves on the first by making the array size dynamic based on user input, and using fewer lines of code to sort the array in-place. The document concludes that the second method is better than the first.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Prepared by Dr\Kadry Ali

1st method:
#include<iostream>
using namespace std;

int main(){
//declaring array
int array[5];
cout<<"Enter 5 numbers randomly : "<<endl;
for(int i=0; i<5; i++)
{
//Taking input in array
cin>>array[i];
}
cout<<endl;
cout<<"Input array is: "<<endl;

for(int j=0; j<5; j++)


{
//Displaying Array
cout<<"\t value at"<<j<<" Index: "<<array[j]<<endl;

}
cout<<endl;
// Bubble Sort Starts Here
int temp;
for(int i2=0; i2<=4; i2++)
{
for(int j=0; j<4; j++)
{
//Swapping element in if statement
if(array[j]>array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
// Displaying Sorted array
cout<<" Sorted Array is: "<<endl;
for(int i3=0; i3<5; i3++)
{
cout<<"\t\t value at"<<i3<<" Index:"<<array[i3]<<endl;
}
return 0;
}
2nd method is better than 1st method
2nd method:
#include<iostream>

using namespace std;

int main()
{
int a[50],n,i,j,temp;
cout<<"Enter the size of array: ";
cin>>n;
cout<<"Enter the array elements: ";

for(i=0;i<n;++i)
cin>>a[i];

for(i=1;i<n;++i)
{
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

cout<<"Array after bubble sort:";


for(i=0;i<n;++i)
cout<<" "<<a[i];

return 0;
}

You might also like