问题
I'm trying to create an array that sorts numbers. It doesn't give me an error message but instead an infinite loop of the input numbers trying to do something. I need to sort the numbers in the array using this method but I can't seem to find where I went wrong.
@echo off
setlocal enabledelayedexpansion
set n=
set n=1
rem *** Section 1 "Input data into num array"
:Input
set v=
set /p v=enter a value:
if !v!== goto Input
set /a v=!v!
set num[!n!]=
set num[!n!]=!v!
set /a n=!n!+1
if !n! lss 6 goto Input
set /a n=!n!-1
rem *** Section 2 "comparing array value"
:A
set i=0
:B
set i=!i!+1
set swp=0
echo !num[%i%]! gtr !num[%j%]! goto D
set /a j=!i!+1
if !num[%i%]! gtr !num[%j%]! goto D
rem *** Section 3 "NO Swap needed"
:E
if !j! lss !n! goto B
rem *** Section 4 "Swap needed"
:D
set swp=1
set tmp=!num[%i%]!
set num[!i!]=!num[%j%]!
set num[!j!]=!tmp!
echo !num[!i!]!, !num[%j%]!
if !j! lss !n! goto B
goto A
:X
!echo[1]!
!echo[2]!
!echo[3]!
!echo[4]!
!echo[5]!
pause
endlocal
回答1:
Mostly, it's just a case of expanding with the right method, in the right order, at the right time.
* Updated to show a way to sort between min / max values and adjust non compliant values *
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
:main
cls
FOR /L %%a in (1,1,5) DO (
Set /p Array[%%a]=Enter New Value for Array[%%a]:
cls
(
If Not Defined Array[%%a] GOTO main
)
)
REM Use For /L loops to set min / max values for arrays if appropriate
:compare_min
cls
Set "min[1]=3"
Set "min[2]=4"
Set "min[3]=5"
Set "min[4]=6"
Set "min[5]=7"
:compare_max
Set "max[1]=8"
Set "max[2]=9"
Set "max[3]=10"
Set "max[4]=11"
Set "max[5]=12"
:min_Val
FOR /L %%a in (1,1,5) DO (
IF !Array[%%a]! LSS !min[%%a]! (
ECHO Array[%%a] Value !Array[%%a]! Below required Value !min[%%a]!
Set /p Array[%%a]=Enter New Value for Array[%%a]:
cls
GOTO min_val
)
)
:max_Val
FOR /L %%a in (1,1,5) DO (
IF !Array[%%a]! GTR !max[%%a]! (
ECHO Array[%%a] Value !Array[%%a]! Exceeds required Value !max[%%a]!
Set /p Array[%%a]=Enter New Value for Array[%%a]:
cls
GOTO min_val
)
)
FOR /L %%a in (1,1,5) DO ECHO Array[%%a] = !Array[%%a]!
ECHO.
::: Access Single Target (3 in example) FOR /L %%a in (3,1,3) DO ECHO Array[%%a] = !Array[%%a]!
::: Access From X Steps Y Range Z (From 3 in steps of 1 to 5. 3,4,5 in example)
::: FOR /L %%a in (3,1,5) DO ECHO Array[%%a] = !Array[%%a]!
pause
Hopefully that will get you on the right track.
Addition, with regards to my comment, A way to Load in Array Values:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
:main
cls
FOR /F "tokens=* USEBACKQ Delims=*" %%c in ("predefined.txt") do (
Set /a "Val+=1"
SET "Array[!Val!]=%%c"
)
:display
FOR /L %%a in (1,1,5) DO ECHO Array[%%a] = !Array[%%a]!
pause
* predefined.txt * example
*20
*40
*60
*80
*100
来源:https://stackoverflow.com/questions/59516467/sorting-numbers-within-an-array-batch-script