# Daily HackerRank Challenge - Day 26

Daily HackerRank Challenge (30 Part Series)

This is a series of Daily HackerRank Challenge. Each day I show the some solutions written in C++.

# Bubble Sort

A standard bubble sort algorithm

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]);
}
}
}


However, we can further optimize to skip the unnecessary cases

bool swapped;
for (int i = 0; i < n; i++) {
swapped = false;
for (int j = 0; j < n - 1; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
swapped=true;
}
}
if(!swapped) break;
}


Final Solution

void countSwaps(vector<int> a) {
int sz = (int)a.size();
int swaps = 0;
bool swapped;
for(int i=0;i<sz;i++){
swapped = false;
for(int j=0;j<sz-1;j++){
if(a[j]>a[j+1]){
swap(a[j],a[j+1]);
swaps++;
swapped=true;
}
}
if(!swapped) break;
}
cout << "Array is sorted in " << swaps << " swaps.\n";
cout << "First Element: " << a[0] << "\n";
cout << "Last Element: " << a[sz-1] << "\n";
}


# Mark and Toys

Sort the array in ascending order

sort(prices.begin(),prices.end());


and track how many items can be bought given the budget.

Final Solution

int maximumToys(vector<int> prices, int k) {
sort(prices.begin(),prices.end());
int ans=0,sum=0;
for(int p:prices){
sum+=p;
if(sum>k){
break;
}
ans++;
}
return ans;
}


# Complete Code

Check out the complete code via below links

Daily HackerRank Challenge (30 Part Series)

Posted on by:

### Wing-Kam

Consultant by day. Developer by night. AWS certified. Exploring #CloudNative currently.