Solution for Sort array until 3 elements are in order, and leave the rest as they are [closed]

is Given Below:

I’m trying to sort an array until the first 3 elements are in the correct order and immediately return the resulting array.

For example if given the array

`const arr = [77, 9, 3, 5, 1]`

would return `[1, 3, 5, 77, 9]`

I tried using the default `sort`

method but I couldn’t figure out how to stop it when 3 elements are in the correct order.

I’ve put numbers here for simplicity. The elements I need to sort are not numbers.

Any help is much appreciated.

Thanks.

well there are couple of ways you can do it, here is a simple solution.

```
arr = [77, 9, 3, 5, 1];
arr2 =[];
arr2.push(...arr.splice(arr.indexOf(Math.min(...arr)), 1));
arr2.push(...arr.splice(arr.indexOf(Math.min(...arr)), 1));
arr2.push(...arr.splice(arr.indexOf(Math.min(...arr)), 1));
result = [...arr2,...arr];
```

this will take 3 smallest element from arr and push it to second array and then you can combine 2 arrays to get your desired result.

Since we only need the first three items to be sorted, **we can use a backwards bubble sort** algo.

- After three passes the first three items will always be the smallest.

**Here’s what it looks like in our case:**

```
let arr = [77, 9, 3, 5, 1];
// Using a bubble sort starting from the back,
// we know that after 3 passes the first three items will be sorted
for (let i = 0; i < 3; i++) {
for (let j = arr.length - 1; j !== 0; j--) {
let current = arr[j];
let behind = arr[j - 1];
if (current < behind) {
arr[j] = arr[j - 1];
arr[j - 1] = current;
}
}
}
console.log(arr);
```