Sorting: Bubble Sort
Problem Statement :
Consider the following version of Bubble Sort: for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1; j++) { // Swap adjacent elements if they are in decreasing order if (a[j] > a[j + 1]) { swap(a[j], a[j + 1]); } } } Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following three lines: 1. Array is sorted in numSwaps swaps., where numSwap is the number of swaps that took place. 2. First Element: firstElement, where firstElement is the first element in the sorted array. 3. Last Element: lastElement, where lastElement is the last element in the sorted array. Hint: To complete this challenge, you must add a variable that keeps a running tally of all swaps that occur during execution. Example a = [ 6, 1, 4 ] swap a 0 [6,4,1] 1 [4,6,1] 2 [4,1,6] 3 [1,4,6] The steps of the bubble sort are shown above. It took swaps to sort the array. Output is: Array is sorted in 3 swaps. First Element: 1 Last Element: 6 Function Description Complete the function countSwaps in the editor below. countSwaps has the following parameter(s): int a[n]: an array of integers to sort Prints Print the three lines required, then return. No return value is expected. Input Format The first line contains an integer,n , the size of the array a. The second line contains n space-separated integers a[ i ]. Constraints 2 <= n <= 600 1 <= a[ i ] <= 2* 10^6
Solution :
Solution in C :
In C :
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
int n;
scanf("%d",&n);
int *a = malloc(sizeof(int) * n);
for(int a_i = 0; a_i < n; a_i++){
scanf("%d",&a[a_i]);
}
int t=0;
for (int i = 0; i < n; i++) {
// Track number of elements swapped during a single array traversal
int numberOfSwaps = 0;
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1]) {
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
t++;
numberOfSwaps++;
}
}
// If no elements were swapped during a traversal, array is sorted
if (numberOfSwaps == 0) {
break;
}
}
printf("Array is sorted in %d swaps.\n",t);
printf("First Element: %d\n",a[0]);
printf("Last Element: %d\n",a[n-1]);
return 0;
}
Solution in C++ :
In C ++ :
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main(){
int n,temp,c=0;
cin >> n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
c++;
}
}
if(c==0)
{
break;
}}
cout<<"Array is sorted in "<<c<<" swaps."<<endl;
cout<<"First Element:"<<" "<<a[0]<<endl;
cout<<"Last Element:"<<" "<<a[n-1]<<endl;
return 0;
}
Solution in Java :
In Java :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int a[] = new int[n];
for(int a_i=0; a_i < n; a_i++){
a[a_i] = in.nextInt();
}
bubbleSort(a);
}
public static void bubbleSort(int[] a){
int numSwaps = 0;
for(int i=0; i< a.length; i++){
for(int j=0; j < a.length - 1; j++){
if(a[j] > a[j+1]){
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
numSwaps++;
}
}
if(numSwaps==0)
break;
}
System.out.println("Array is sorted in " + numSwaps +" swaps.");
System.out.println("First Element: " + a[0]);
System.out.println("Last Element: " + a[a.length-1]);
}
}
Solution in Python :
In Python3 :
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
swap=0
for i in range (0,len(a)):
for j in range (0,len(a)-1):
if a[j]>a[j+1]:
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
swap+=1
print("Array is sorted in",swap,"swaps.")
print("First Element:",a[0])
print("Last Element:",a[len(a)-1])
View More Similar Problems
Queries with Fixed Length
Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon
View Solution →QHEAP1
This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element
View Solution →Jesse and Cookies
Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t
View Solution →Find the Running Median
The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.
View Solution →Minimum Average Waiting Time
Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h
View Solution →Merging Communities
People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w
View Solution →