Check out the resources on the page's right side to learn more about bubble sort. The video tutorial is by Gayle Laakmann McDowell, author of the best-selling interview book Cracking the Coding Interview.
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:
Array is sorted in numSwaps swaps.
, where is the number of swaps that took place.First Element: firstElement
, where is the first element in the sorted array.Last Element: lastElement
, where 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.
For example, given a worst-case but small array to sort: we go through the following steps:
swap a
0 [6,4,1]
1 [4,6,1]
2 [4,1,6]
3 [1,4,6]
It took swaps to sort the array. Output would be
Array is sorted in 3 swaps.
First Element: 1
Last Element: 6
Function Description
Complete the function countSwaps in the editor below. It should print the three lines required, then return.
countSwaps has the following parameter(s):
- a: an array of integers .
Input Format
The first line contains an integer, , the size of the array .
The second line contains space-separated integers .
The second line contains space-separated integers .
Constraints
Output Format
You must print the following three lines of output:
Array is sorted in numSwaps swaps.
, where is the number of swaps that took place.First Element: firstElement
, where is the first element in the sorted array.Last Element: lastElement
, where is the last element in the sorted array.
Sample Input 0
3
1 2 3
Sample Output 0
Array is sorted in 0 swaps.
First Element: 1
Last Element: 3
Explanation 0
The array is already sorted, so swaps take place and we print the necessary three lines of output shown above.
The array is already sorted, so swaps take place and we print the necessary three lines of output shown above.
Sample Input 1
3
3 2 1
Sample Output 1
Array is sorted in 3 swaps.
First Element: 1
Last Element: 3
Explanation 1
The array is not sorted, and its initial values are: . The following swaps take place:
The array is not sorted, and its initial values are: . The following swaps take place:
At this point the array is sorted and we print the necessary three lines of output shown above.
Sorting: Bubble Sort - Hacker Rank Solution
Bubble sort is approach to sort an array. At every iteration we try to put the maximum element in range at position where . There are a total of elements, so if we run this iteration times we are done. The below is the code snippet for the idea above.
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]);
}
}
}
To query how many times we have swapped the elements, we can just keep track of a counter and increment it by whenever we swap the elements in the code above.
Problem Setter's code:
void countSwaps(vector<int> a) {
int cnt=0;
int n=a.size();
for(int i=0;i<n;i++)
{
for(int j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
swap(a[j],a[j+1]);
cnt++;
}
}
}
cout<<"Array is sorted in "<<cnt<<" swaps."<<endl;
cout<<"First Element: "<<a[0]<<endl;
cout<<"Last Element: "<<a[a.size()-1]<<endl;
}
Problem Tester's code:
Java
import java.util.Scanner;
public class Solution {
private static int[] array;
private static void bubbleSort() {
int n = array.length;
// number of swaps for all array iterations
int totalSwaps = 0;
for (int i = 0; i < n; i++) {
// number of swaps for current array iteration
int numSwaps = 0;
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
numSwaps++;
totalSwaps++;
}
}
if (numSwaps == 0) {
System.out.printf("Array is sorted in %d swaps.\n", totalSwaps);
System.out.printf("First Element: %d\n", array[0]);
System.out.printf("Last Element: %d\n", array[n - 1]);
break;
}
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
in.close();
bubbleSort();
}
}
Python 3
import sys
n = int(input())
a = [int(i) for i in input().strip().split(' ')]
numSwaps = 0
for i in range(n):
currentSwaps = 0
for j in range(0, n - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
currentSwaps += 1
numSwaps += currentSwaps
if currentSwaps == 0:
break
print("Array is sorted in " + str(numSwaps) + " swaps.")
print("First Element: " + str(a[0]))
print("Last Element: " + str(a[-1]))
void countSwaps(vector a)
ReplyDelete{
int n=a.size();
bool swapped;
int swaps=0;
for(int i=0;ia[j+1])
{
swap(a[j],a[j+1]);
swapped=true;
swaps+=1;
}
}
if(!swapped)
break;
}
cout<<"Array is sorted in "<<swaps<<" swaps."<<endl;
cout<<"First Element: "<<a[0]<<endl;
cout<<"Last Element: "<<a[n-1]<<endl;
}
//this code avoids unnecessary loopings.
import java.util.Scanner;
ReplyDeletepublic class Solution {
private static int[] array;
private static void bubbleSort() {
int n = array.length;
// number of swaps for all array iterations
int totalSwaps = 0;
for (int i = 0; i < n; i++) {
// number of swaps for current array iteration
int numSwaps = 0;
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
numSwaps++;
totalSwaps++;
}
}
if (numSwaps == 0) {
System.out.printf("Array is sorted in %d swaps.\n", totalSwaps);
System.out.printf("First Element: %d\n", array[0]);
System.out.printf("Last Element: %d\n", array[n - 1]);
break;
}
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = in.nextInt();
}
in.close();
bubbleSort();
}
}