Wipro Coding Question 2

Bubble Sort

 

Here, in this page we will discuss the Wipro coding question asked in previous recruitment drive. We will  write an efficient algorithm for bubble sort and there solution in C++ and Java. 

Bubble sort

Question 2

Write a program to implement a bubble sort algorithm for sorting the elements of an array. We are given with a array of N elements and we need to sort them in ascending order. But in this question we need to use Bubble sort, to sort the given array.

Input Format:

  • The first line corresponds to the size of an array.
  • The second line corresponds to the elements.

Output Format:

Print the N elements of the array in ascending order.

Sample Input:

6

11 15 26 38 9 10 

Sample Output:

9 10 11 15 26 38

Explanation :

Here, we have 6 elements and array elements are 11 15 26 38 9 10, Sorted array in ascending order will be 9 10 11 15 26 38.

#include<bits/stdc++.h>
using namespace std;

int main(){

int n;
cin>>n;

vector <int> a(n);

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

for(int i=n-1; i>=0; i--){

for(int j=0; j<i;j++){

if(a[j]>a[j+1]){

int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}

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

return 0;
}
import java.util.*;
class Solution
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int countOfSwap=0;
for(int i=0;i<n-1;i++)
{
countOfSwap=0;
for(int j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
countOfSwap++;
}
}
if(countOfSwap==0)
break;
}
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ");
}
}