--- id: 69bc6cb30c1d112a2e110a05 title: "Challenge 248: Sorted Array Swap" challengeType: 29 dashedName: challenge-248 --- # --description-- Given an array of integers, return a new array using the following rules: 1. Sort the integers in ascending order 2. Then swap all values whose index is a multiple of 3 with the value before it. # --hints-- `sort_and_swap([3, 1, 2, 4, 6, 5])` should return `[1, 2, 4, 3, 5, 6]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(sort_and_swap([3, 1, 2, 4, 6, 5]), [1, 2, 4, 3, 5, 6])`) }}) ``` `sort_and_swap([9, 7, 5, 3, 1, 2, 4, 6, 8])` should return `[1, 2, 4, 3, 5, 7, 6, 8, 9]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(sort_and_swap([9, 7, 5, 3, 1, 2, 4, 6, 8]), [1, 2, 4, 3, 5, 7, 6, 8, 9])`) }}) ``` `sort_and_swap([1, 2, 3, 4, 5, 6, 7, 8, 9])` should return `[1, 2, 4, 3, 5, 7, 6, 8, 9]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(sort_and_swap([1, 2, 3, 4, 5, 6, 7, 8, 9]), [1, 2, 4, 3, 5, 7, 6, 8, 9])`) }}) ``` `sort_and_swap([12, 5, 8, 1, 3, 10, 2, 7, 6, 4, 9, 11])` should return `[1, 2, 4, 3, 5, 7, 6, 8, 10, 9, 11, 12]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(sort_and_swap([12, 5, 8, 1, 3, 10, 2, 7, 6, 4, 9, 11]), [1, 2, 4, 3, 5, 7, 6, 8, 10, 9, 11, 12])`) }}) ``` `sort_and_swap([100, -50, 0, 75, -25, 50, -75, 25])` should return `[-75, -50, 0, -25, 25, 75, 50, 100]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(sort_and_swap([100, -50, 0, 75, -25, 50, -75, 25]), [-75, -50, 0, -25, 25, 75, 50, 100])`) }}) ``` `sort_and_swap([5, 9, 13, 77, 88, 313, -10, -65, 0, 8, 99, 101, -4, 2])` should return `[-65, -10, 0, -4, 2, 8, 5, 9, 77, 13, 88, 101, 99, 313]`. ```js ({test: () => { runPython(` from unittest import TestCase TestCase().assertEqual(sort_and_swap([5, 9, 13, 77, 88, 313, -10, -65, 0, 8, 99, 101, -4, 2]), [-65, -10, 0, -4, 2, 8, 5, 9, 77, 13, 88, 101, 99, 313])`) }}) ``` # --seed-- ## --seed-contents-- ```py def sort_and_swap(arr): return arr ``` # --solutions-- ```py def sort_and_swap(arr): result = sorted(arr) for i in range(3, len(result), 3): result[i], result[i - 1] = result[i - 1], result[i] return result ```