Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Hacker Rank] Interview Preparation Kit: Sorting: Bubble Sort. Solved ✅. #454

Merged
merged 1 commit into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions docs/hackerrank/interview_preparation_kit/sort/ctci-bubble-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# [Sorting: Bubble Sort](https://www.hackerrank.com/challenges/ctci-bubble-sort/)

Find the minimum number of conditional checks taking place in Bubble Sort

- Difficulty: `#easy`
- Category: `#ProblemSolvingBasic` `#sorting`

Consider the following version of Bubble Sort:

```c
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 *`numSums`* 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

```text
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 `3` swaps to sort the array.
Output is:

```text
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 \leq n \leq 600 $
- $ a \leq a[i] \leq 2 \times 10^6 $

## Output Format

## Sample Input 0

```text
STDIN Function
----- --------
3 a[] size n = 3
1 2 3 a = [1, 2, 3]
```

## Sample Output 0

```text
Array is sorted in 0 swaps.
First Element: 1
Last Element: 3
Explanation 0
```

The array is already sorted, so `0` swaps take place.

## Sample Input 1

```text
3
3 2 1
```

## Sample Output 1

```text
Array is sorted in 3 swaps.
First Element: 1
Last Element: 3
```

## Explanation 1

The array is not sorted, and its initial values are: `{1, 2, 3}`.
The following `3` swaps take place:

```text
{3, 2, 1} -> {2, 3, 1}
{2, 3, 1} -> {2, 1, 3}
{2, 1, 3} -> {1, 2, 3}
```

At this point the array is sorted and the three lines of output are printed to stdout.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { describe, expect, it } from '@jest/globals';

import { countSwaps, SortableGroup } from './ctci_bubble_sort';
import TEST_CASES from './ctci_bubble_sort.testcases.json';

describe('countSwaps', () => {
it('build tree and flattened tree test cases', () => {
expect.assertions(6);

TEST_CASES.forEach((test) => {
const sortable = new SortableGroup(test.input);
const resultSort = sortable.bubble_sort().group;
const resultPrint = countSwaps(test.input);

expect(resultPrint).toBeUndefined();
expect(resultSort).toStrictEqual(test.sorted);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"input": [6, 4, 1],
"sorted": [1, 4, 6],
"expected": "Array is sorted in 3 swaps.\nFirst Element: 1\nLast Element: 6\n"
},
{
"input": [3, 2, 1],
"sorted": [1, 2, 3],
"expected": "Array is sorted in 3 swaps.\nFirst Element: 1\nLast Element: 3\n"
},
{
"input": [1, 2, 3],
"sorted": [1, 2, 3],
"expected": "Array is sorted in 0 swaps.\nFirst Element: 1\nLast Element: 3\n"
}
]
55 changes: 55 additions & 0 deletions src/hackerrank/interview_preparation_kit/sort/ctci_bubble_sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/sort/ctci-bubble-sort.md]]
*/

const SEPARATOR = '\n';

export class SortableGroup {
group: number[];

count: number;

constructor(group: number[]) {
this.count = 0;
this.group = group;
}

bubble_sort(): this {
const group = [...this.group];
const size: number = group.length;
let count = 0;
let i = 0;

while (i < size) {
for (let j = 0; j < size - 1; j++) {
if (group[j] > group[j + 1]) {
[group[j], group[j + 1]] = [group[j + 1], group[j]];

count += 1;
}
}
i += 1;
}

this.count = count;
this.group = group;

return this;
}
}

export function countSwaps(a: number[]): void {
const sortableGroup = new SortableGroup(a);
sortableGroup.bubble_sort();

const last = sortableGroup.group.length - 1;

const output =
`Array is sorted in ${sortableGroup.count} swaps.${SEPARATOR}` +
`First Element: ${sortableGroup.group[0]}${SEPARATOR}` +
`Last Element: ${sortableGroup.group[last]}${SEPARATOR}`;

console.log(output);
}

export default { countSwaps, SortableGroup };