A
A
Andrey2019-02-26 20:03:34
bash
Andrey, 2019-02-26 20:03:34

How to reverse the elements of an array?

Lord, please, I beg you, I no longer know what to read, what to press, what gods to pray to...? It is necessary to reverse the array elements between the maximum and minimum:
input 1 2 3 4 5
output 1 4 3 2 5

#!/bin/bash

read N
arr=($(cat))

maxPos=0
minPos=0
j=0

for ((i=0; i < N; i++))
do
  if ((${arr[minPos]} > ${arr[i]}))
  then
    minPos=$i
    fi
    
    if ((${arr[maxPos]} < ${arr[i]}))
    then
    maxPos=$i
    fi
done

if (($minPos<$maxPos))
then
  first=$minPos
  second=$maxPos
else
    first=$maxPos
    second=$minPos
fi

for ((i=0; i<first; i++))
do
  echo ${arr[i]}
done

for ((i=second; i>=first; i--))
do
  echo ${arr[i]}
done

for ((i=second+1; i<N; i++))
do
  echo ${arr[i]}
done

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey, 2019-02-26
@officialandrey

Everything has already solved the problem.
In case anyone needs it, here is the code:

#!/bin/bash

read N
arr=($(cat))

maxPos=0
minPos=0
j=0

for ((i=0; i < N; i++))
do
  if ((${arr[minPos]} > ${arr[i]}))
  then
    minPos=$i
    fi
    
    if ((${arr[maxPos]} < ${arr[i]}))
    then
    maxPos=$i
    fi
done

if (($minPos<$maxPos))
then
  first=$minPos
  second=$maxPos
else
    first=$maxPos
    second=$minPos
fi

for ((i=0; i<first+1; i++))
do
  echo ${arr[i]}
done

for ((i=second-1; i>=first+1; i--))
do
  echo ${arr[i]}
done

for ((i=second; i<N; i++))
do
  echo ${arr[i]}
done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question