In c++
#include <iostream>
using namespace std;
int main()
{
int temp=0;
int swap=0,comp=0;
int a[3];
cout<<"Enter 3 numbers"<<endl;
for (int i = 0; i < 3; ++i)
{
cin>>a[i];
}
cout<<endl;
cout<<"The list you enterd"<<endl;
for (int i = 0; i < 3; ++i)
{
cout<<a[i]<<" ";
}
cout<<endl;
for (int i = 1; i < 3; ++i)
{
for (int j = 0; j < 3-i; j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
swap++;
}
comp++;
}
}
cout<<endl;
cout<<"The sorted list"<<endl;
for (int i = 0; i < 3; ++i)
{
/* code */
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"The number of swaps "<<swap<<endl;
cout<<"The number of comparision "<<comp<<endl;
}
in python
a=[5,61,1]
swap=0
comp=0
leng=len(a)
for i in range(1,leng):
for j in range(0,leng-i):
if a[j]>a[j+1]:
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
swap+=1
comp+=1
print("The sorted list")
for i in a:
print(i,end=" ")
print()
print("Total number of comparison {}".format(comp))
print("Total number of swap %d"%swap)
in ruby
a=[5,61,1]
comp=0
swap=0
for i in (1...a.size)
for j in (0...a.size-i)
if a[j]>a[j+1]
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
swap+=1
end
comp+=1
end
end
puts
puts "The sorted list"
a.each_index do |num|
print " #{a[num]}"
end
puts
puts " Total number of comparision #{comp}"
puts " Total number of swaps #{swap}"
Top comments (0)