{ }codelper
swapping elementslist indexingP0317

Shortest to the front, tallest to the back

In gym class, n students stand in one line. The teacher tidies the line with exactly two swaps. First, the shortest student and the student at the front of the line swap places. If several students are the shortest, the one standing nearest the front among them is the one who swaps. Second, in the line after the first swap, the tallest student and the student at the back of the line swap places. If several students are the tallest, the one standing nearest the back among them is the one who swaps. If the student who should swap is already standing in that place, nothing happens. The first line gives n, and the second line gives the students' heights from front to back, separated by single spaces. Print the heights of the line after the two swaps, from front to back, on one line separated by single spaces.

Input
1 ≤ n ≤ 1,000.
Each height is an integer from 100 to 200
Output
One line: the n heights after the two swaps
Example 1 · stdin
4
180 160 150 170
stdout
150 160 170 180
Example 2 · stdin
6
160 150 175 150 175 160
stdout
150 160 175 150 160 175
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The tools for finding a position and swapping two slots differ by language.
First position of a value: Python a.index(v), JS/TS a.indexOf(v), C# Array.IndexOf(a, v), C++ std::min_element (it returns something that points at the element), Craykon a.IndexOf(v).
Last position: JS/TS a.lastIndexOf(v), C# Array.LastIndexOf(a, v), and in C++ you look from the back, as in std::max_element(a.rbegin(), a.rend()).
Python lists have no method that searches from the back, so search the reversed list and convert the position; Java arrays, C and Craykon use a loop.
In a loop, comparing with < keeps the first position and comparing with >= keeps the last.
Swapping: Python a[0], a[i] = a[i], a[0], JS/TS [a[0], a[i]] = [a[i], a[0]], C# (a[0], a[i]) = (a[i], a[0]), C++ std::swap(a.front(), *it); Java, C and Craykon use a temporary variable.
Five traps: (1) If you find both positions first and then do the two swaps, then when the tallest student was at the front the first swap moves that student, and the position you wrote down is stale (example 1 becomes 170 160 180 150).
Find the second position after the first swap.
(2) In Python, if you write the position lookup directly on the left side, as in a[0], a[a.index(min(a))] = a[a.index(min(a))], a[0], the left side is assigned one target at a time from the left, so a.index(min(a)) is evaluated again after the smallest value has been stored in a[0], and it is now 0.
The value just stored is overwritten at once and the swap is undone (example 1 becomes 170 160 150 180).
Store the position in a variable first.
(3) When several heights are equal: finding the smallest with <= picks the last position, and C++ std::max_element(a.begin(), a.end()) and Python a.index(max(a)) give the first position.
The value is the same, but the swap partner differs, so the line differs (example 2).
(4) The XOR trick in C, *x ^= *y; *y ^= *x; *x ^= *y;, XORs a value with itself and leaves 0 when both addresses are the same slot.
That is exactly what happens when the shortest student is already at the front.
(5) Writing a[0] = a[i]; a[i] = a[0]; without a temporary wipes out the old a[0] in the first statement, so both slots end up equal.

Pythonmain.py · 12 lines
n = int(input())a = list(map(int, input().split())) # 가장 작은 키가 처음 나오는 자리를 먼저 변수에 담아 두고 맞바꾼다i = a.index(min(a))a[0], a[i] = a[i], a[0] # 가장 큰 키는 첫째 맞바꾸기를 마친 줄에서 다시 찾는다. 뒤집은 줄에서 처음 나오는 자리가 마지막 자리다j = n - 1 - a[::-1].index(max(a))a[n - 1], a[j] = a[j], a[n - 1] print(*a)
JavaScriptmain.js · 13 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const a = lines[1].trim().split(/\s+/).map(Number); // 가장 작은 키가 처음 나오는 자리const i = a.indexOf(Math.min(...a));[a[0], a[i]] = [a[i], a[0]]; // 가장 큰 키는 첫째 맞바꾸기를 마친 줄에서 다시 찾는다. lastIndexOf는 마지막으로 나오는 자리를 준다const j = a.lastIndexOf(Math.max(...a));[a[n - 1], a[j]] = [a[j], a[n - 1]]; console.log(a.join(" "));
TypeScriptmain.ts · 14 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const a: number[] = lines[1].trim().split(/\s+/).map(Number); // 가장 작은 키가 처음 나오는 자리const i: number = a.indexOf(Math.min(...a));[a[0], a[i]] = [a[i], a[0]]; // 가장 큰 키는 첫째 맞바꾸기를 마친 줄에서 다시 찾는다. lastIndexOf는 마지막으로 나오는 자리를 준다const j: number = a.lastIndexOf(Math.max(...a));[a[n - 1], a[j]] = [a[j], a[n - 1]]; console.log(a.join(" "));
JavaMain.java · 38 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main {    // Java에는 한 줄 맞바꾸기가 없다. 배열과 두 자리를 받아 임시 변수로 바꾼다    static void swap(int[] a, int i, int j) {        int tmp = a[i];        a[i] = a[j];        a[j] = tmp;    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        int[] a = new int[n];        StringTokenizer st = new StringTokenizer(in.readLine());        for (int k = 0; k < n; k++) a[k] = Integer.parseInt(st.nextToken());         // 가장 작은 키가 처음 나오는 자리: 더 작을 때만(<) 바꾼다        int i = 0;        for (int k = 1; k < n; k++) if (a[k] < a[i]) i = k;        swap(a, 0, i);         // 첫째 맞바꾸기를 마친 줄에서, 가장 큰 키가 마지막으로 나오는 자리: 같을 때도(>=) 바꾼다        int j = 0;        for (int k = 1; k < n; k++) if (a[k] >= a[j]) j = k;        swap(a, n - 1, j);         StringBuilder out = new StringBuilder();        for (int k = 0; k < n; k++) {            if (k > 0) out.append(' ');            out.append(a[k]);        }        System.out.println(out);    }}
C#Main.cs · 21 lines
using System;using System.Linq; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine().Trim());        int[] a = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();         // 가장 작은 키가 처음 나오는 자리        int i = Array.IndexOf(a, a.Min());        (a[0], a[i]) = (a[i], a[0]);         // 가장 큰 키는 첫째 맞바꾸기를 마친 줄에서 다시 찾는다. LastIndexOf는 마지막으로 나오는 자리를 준다        int j = Array.LastIndexOf(a, a.Max());        (a[n - 1], a[j]) = (a[j], a[n - 1]);         Console.WriteLine(string.Join(" ", a));    }}
C++main.cpp · 21 lines
#include <algorithm>#include <iostream>#include <vector> int main() {    int n;    std::cin >> n;    std::vector<int> a(n);    for (int& x : a) std::cin >> x;     // min_element는 가장 작은 값이 처음 나오는 자리를 가리킨다    auto smallest = std::min_element(a.begin(), a.end());    std::swap(a.front(), *smallest);     // max_element도 처음 나오는 자리를 준다. 뒤에서부터 보면(rbegin) 마지막으로 나오는 자리가 된다    auto tallest = std::max_element(a.rbegin(), a.rend());    std::swap(a.back(), *tallest);     for (int k = 0; k < n; k++) std::cout << (k ? " " : "") << a[k];    std::cout << '\n';}
Cmain.c · 29 lines
#include <stdio.h> /* 값이 아니라 칸의 주소를 받아야 배열이 바뀐다 */static void swap(int *x, int *y) {    int tmp = *x;    *x = *y;    *y = tmp;} int main(void) {    int n;    static int a[1000];    scanf("%d", &n);    for (int k = 0; k < n; k++) scanf("%d", &a[k]);     /* 가장 작은 키가 처음 나오는 자리: 더 작을 때만(<) 바꾼다 */    int i = 0;    for (int k = 1; k < n; k++) if (a[k] < a[i]) i = k;    swap(&a[0], &a[i]);     /* 첫째 맞바꾸기를 마친 줄에서, 가장 큰 키가 마지막으로 나오는 자리: 같을 때도(>=) 바꾼다 */    int j = 0;    for (int k = 1; k < n; k++) if (a[k] >= a[j]) j = k;    swap(&a[n - 1], &a[j]);     for (int k = 0; k < n; k++) printf(k ? " %d" : "%d", a[k]);    printf("\n");    return 0;}
Craykonmain.cray · 34 lines
// 두 자리를 맞바꾼다. 목록은 넘겨받은 그 목록이 바뀐다맞바꾸기(줄, i, j){    임시 = 줄[i];    줄[i] = 줄[j];    줄[j] = 임시;} n = Console.ReadLine().ToNumber();a = Console.ReadNumbers(); // 가장 작은 키가 처음 나오는 자리: 더 작을 때만(<) 바꾼다i = 0;for (k = 1; k < n; k++){    if (a[k] < a[i])    {        i = k;    }}맞바꾸기(a, 0, i); // 첫째 맞바꾸기를 마친 줄에서, 가장 큰 키가 마지막으로 나오는 자리: 같을 때도(>=) 바꾼다j = 0;for (k = 1; k < n; k++){    if (a[k] >= a[j])    {        j = k;    }}맞바꾸기(a, n - 1, j); Console.WriteLine(a);